From ccd92fa02f88b8cd0abeb9b90af5edded7be3d92 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 18:22:51 +0000 Subject: [PATCH 01/12] perf(client): share one cached DNS lookup per host across sessions Every Session builds its own reqwest client, and reqwest's default resolver runs an uncached getaddrinfo per new connection. When hundreds of sessions open at once the burst overflows local stub resolvers (systemd-resolved drops the excess, glibc retries after 5 s), so part of the opens stall for 5 s or more. Route every kernel client through a process-wide resolver that runs one lookup per host at a time and reuses a successful answer for 30 s. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 3 + src/client/dns.rs | 254 +++++++++++++++++++++++++++++++++++++++++++++ src/client/http.rs | 3 +- src/client/mod.rs | 1 + 4 files changed, 260 insertions(+), 1 deletion(-) create mode 100644 src/client/dns.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..8469524b 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,6 +20,9 @@ changes go in their respective binding's NEXT_CHANGELOG. with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in `adbc.databricks.http.headers` is now rejected; use the dedicated entry option. +- All HTTP clients in a process share one DNS lookup per host at a time and + reuse a successful answer for 30 s, so many sessions opening at once no + longer send one identical lookup each. ### Updated diff --git a/src/client/dns.rs b/src/client/dns.rs new file mode 100644 index 00000000..39232b08 --- /dev/null +++ b/src/client/dns.rs @@ -0,0 +1,254 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Process-wide DNS cache shared by every kernel HTTP client. +//! +//! Each `Session` owns its own `reqwest::Client`, and reqwest's default +//! resolver runs one uncached `getaddrinfo` per new connection. When hundreds +//! of sessions open at once, the burst of identical lookups overflows local +//! stub resolvers (systemd-resolved drops the excess and glibc retries after +//! its 5 s timeout), so a share of the opens stall for 5 s or more. This +//! resolver runs one lookup per host at a time for the whole process and +//! reuses a successful answer for [`TTL`]. Failures are shared with the +//! callers already waiting on that lookup but are not cached. + +use std::collections::HashMap; +use std::io; +use std::net::{SocketAddr, ToSocketAddrs}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use reqwest::dns::{Addrs, Name, Resolve, Resolving}; +use tokio::sync::OnceCell; + +/// How long a successful answer is reused. Matches the JVM's default +/// positive-lookup TTL, so the JDBC driver's behaviour is the reference. +const TTL: Duration = Duration::from_secs(30); +/// Bound on distinct cached hosts (workspace + CloudFetch storage hosts). +const MAX_HOSTS: usize = 256; + +type Lookup = Arc io::Result> + Send + Sync>; +type Answer = (Result, Arc>, Instant); + +pub(crate) struct CachingResolver { + entries: Mutex>>>, + ttl: Duration, + lookup: Lookup, +} + +impl CachingResolver { + /// The resolver every kernel HTTP client in this process uses. + pub(crate) fn shared() -> Arc { + static SHARED: OnceLock> = OnceLock::new(); + SHARED + .get_or_init(|| Arc::new(Self::new(TTL, Arc::new(system_lookup)))) + .clone() + } + + fn new(ttl: Duration, lookup: Lookup) -> Self { + Self { + entries: Mutex::new(HashMap::new()), + ttl, + lookup, + } + } + + /// The lookup to join for `host`: the one in flight, a fresh cached + /// answer, or a new lookup when the last one expired or failed. + fn entry(&self, host: &str) -> Arc> { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + let usable = |cell: &OnceCell| match cell.get() { + None => true, + Some((Ok(_), at)) => at.elapsed() < self.ttl, + Some((Err(_), _)) => false, + }; + if let Some(cell) = entries.get(host) { + if usable(cell) { + return Arc::clone(cell); + } + } + if entries.len() >= MAX_HOSTS { + entries.retain(|_, cell| usable(cell)); + if entries.len() >= MAX_HOSTS { + entries.clear(); + } + } + let cell = Arc::new(OnceCell::new()); + entries.insert(host.to_owned(), Arc::clone(&cell)); + cell + } +} + +impl Resolve for CachingResolver { + fn resolve(&self, name: Name) -> Resolving { + let host = name.as_str().to_owned(); + let cell = self.entry(&host); + let lookup = Arc::clone(&self.lookup); + Box::pin(async move { + let (answer, _) = cell.get_or_init(|| run_lookup(lookup, host)).await; + match answer { + Ok(addrs) => { + let addrs = Arc::clone(addrs); + Ok(Box::new((0..addrs.len()).map(move |i| addrs[i])) as Addrs) + } + Err(e) => Err(io::Error::new(e.kind(), e.to_string()).into()), + } + }) + } +} + +/// Run the blocking lookup on its own thread, not the caller's blocking +/// pool: other sessions wait on this answer, so it must not be cancelled +/// when the session that started it shuts its runtime down. +async fn run_lookup(lookup: Lookup, host: String) -> Answer { + let (tx, rx) = tokio::sync::oneshot::channel(); + let spawned = std::thread::Builder::new() + .name("dbx-sql-kernel-dns".to_owned()) + .spawn(move || { + let _ = tx.send(lookup(&host)); + }); + let result = match spawned { + Err(e) => Err(e), + Ok(_) => match rx.await { + Ok(Ok(addrs)) if addrs.is_empty() => Err(io::Error::new( + io::ErrorKind::NotFound, + "DNS lookup returned no addresses", + )), + Ok(result) => result, + Err(_) => Err(io::Error::other("DNS lookup thread exited")), + }, + }; + (result.map(Arc::from).map_err(Arc::new), Instant::now()) +} + +fn system_lookup(host: &str) -> io::Result> { + Ok((host, 0).to_socket_addrs()?.collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::str::FromStr; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn counting(delay: Duration, fail: bool) -> (Lookup, Arc) { + let calls = Arc::new(AtomicUsize::new(0)); + let c = Arc::clone(&calls); + let lookup: Lookup = Arc::new(move |_host| { + c.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(delay); + if fail { + Err(io::Error::other("boom")) + } else { + Ok(vec!["10.0.0.1:0".parse().unwrap()]) + } + }); + (lookup, calls) + } + + async fn resolve(r: &Arc, host: &str) -> Result, String> { + r.resolve(Name::from_str(host).unwrap()) + .await + .map(|a| a.collect()) + .map_err(|e| e.to_string()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_lookups_for_one_host_share_one_query() { + let (lookup, calls) = counting(Duration::from_millis(50), false); + let r = Arc::new(CachingResolver::new(TTL, lookup)); + let tasks: Vec<_> = (0..64) + .map(|_| { + let r = Arc::clone(&r); + tokio::spawn(async move { resolve(&r, "example.com").await }) + }) + .collect(); + for t in tasks { + assert_eq!( + t.await.unwrap().unwrap(), + vec!["10.0.0.1:0".parse().unwrap()] + ); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + resolve(&r, "example.com").await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1, "fresh answer is reused"); + resolve(&r, "other.example.com").await.unwrap(); + assert_eq!( + calls.load(Ordering::SeqCst), + 2, + "hosts are cached separately" + ); + } + + #[tokio::test] + async fn expired_answers_are_looked_up_again() { + let (lookup, calls) = counting(Duration::ZERO, false); + let r = Arc::new(CachingResolver::new(Duration::from_millis(20), lookup)); + resolve(&r, "example.com").await.unwrap(); + tokio::time::sleep(Duration::from_millis(40)).await; + resolve(&r, "example.com").await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn failures_reach_current_waiters_but_are_not_cached() { + let (lookup, calls) = counting(Duration::from_millis(50), true); + let r = Arc::new(CachingResolver::new(TTL, lookup)); + let tasks: Vec<_> = (0..16) + .map(|_| { + let r = Arc::clone(&r); + tokio::spawn(async move { resolve(&r, "example.com").await }) + }) + .collect(); + for t in tasks { + assert!(t.await.unwrap().unwrap_err().contains("boom")); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(resolve(&r, "example.com").await.is_err()); + assert_eq!( + calls.load(Ordering::SeqCst), + 2, + "a failure is retried by the next caller" + ); + } + + #[tokio::test] + async fn empty_answers_are_errors() { + let lookup: Lookup = Arc::new(|_| Ok(Vec::new())); + let r = Arc::new(CachingResolver::new(TTL, lookup)); + assert!(resolve(&r, "example.com").await.is_err()); + } + + #[test] + fn lookup_survives_the_runtime_that_started_it() { + let (lookup, calls) = counting(Duration::from_millis(100), false); + let r = Arc::new(CachingResolver::new(TTL, lookup)); + let first = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(); + let r1 = Arc::clone(&r); + first.spawn(async move { resolve(&r1, "example.com").await }); + std::thread::sleep(Duration::from_millis(20)); + first.shutdown_background(); + + let second = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + assert!(second.block_on(resolve(&r, "example.com")).is_ok()); + assert!(calls.load(Ordering::SeqCst) <= 2); + } +} diff --git a/src/client/http.rs b/src/client/http.rs index e5f9ad0b..f69acc25 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -522,7 +522,8 @@ impl DatabricksHttpClient { .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) - .redirect(redirect); + .redirect(redirect) + .dns_resolver(crate::client::dns::CachingResolver::shared()); // Apply TLS configuration if config.tls.enabled == Some(false) { diff --git a/src/client/mod.rs b/src/client/mod.rs index af553abf..3b972d5e 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -31,6 +31,7 @@ //! [`transport`]: self::transport //! [`sea`]: self::sea +pub(crate) mod dns; pub mod http; pub mod retry; pub mod sea; From 62044631ca1e6b5d7d1ac2427dc63ef68fce8fef Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 19:11:06 +0000 Subject: [PATCH 02/12] fix(client): let the DNS lookup thread publish its own answer With tokio's OnceCell, a cancelled caller (e.g. reqwest's connect timeout) handed initialization to the next waiter, which started a second lookup and dropped the first thread's answer. The lookup thread now publishes into a watch channel that every waiter reads, so a cancelled caller no longer restarts it. Also rotate the first address per call within the leading address family, as round-robin DNS would. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 163 +++++++++++++++++++++++++++++++++------------- 1 file changed, 116 insertions(+), 47 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index 39232b08..d89f42ab 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -26,11 +26,12 @@ use std::collections::HashMap; use std::io; use std::net::{SocketAddr, ToSocketAddrs}; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; use reqwest::dns::{Addrs, Name, Resolve, Resolving}; -use tokio::sync::OnceCell; +use tokio::sync::watch; /// How long a successful answer is reused. Matches the JVM's default /// positive-lookup TTL, so the JDBC driver's behaviour is the reference. @@ -40,11 +41,15 @@ const MAX_HOSTS: usize = 256; type Lookup = Arc io::Result> + Send + Sync>; type Answer = (Result, Arc>, Instant); +/// `None` while the lookup thread runs; the thread publishes the answer. +type Entry = watch::Receiver>; pub(crate) struct CachingResolver { - entries: Mutex>>>, + entries: Mutex>, ttl: Duration, lookup: Lookup, + /// Rotates the first address handed out, as round-robin DNS would. + next: AtomicUsize, } impl CachingResolver { @@ -61,75 +66,108 @@ impl CachingResolver { entries: Mutex::new(HashMap::new()), ttl, lookup, + next: AtomicUsize::new(0), } } /// The lookup to join for `host`: the one in flight, a fresh cached /// answer, or a new lookup when the last one expired or failed. - fn entry(&self, host: &str) -> Arc> { + fn entry(&self, host: &str) -> Entry { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); - let usable = |cell: &OnceCell| match cell.get() { - None => true, - Some((Ok(_), at)) => at.elapsed() < self.ttl, - Some((Err(_), _)) => false, + let usable = |entry: &Entry| { + let in_flight = match &*entry.borrow() { + None => true, + Some((Ok(_), at)) => return at.elapsed() < self.ttl, + Some((Err(_), _)) => return false, + }; + // An unanswered entry whose thread is gone will never be answered. + in_flight && entry.has_changed().is_ok() }; - if let Some(cell) = entries.get(host) { - if usable(cell) { - return Arc::clone(cell); + if let Some(entry) = entries.get(host) { + if usable(entry) { + return entry.clone(); } } if entries.len() >= MAX_HOSTS { - entries.retain(|_, cell| usable(cell)); + entries.retain(|_, entry| usable(entry)); if entries.len() >= MAX_HOSTS { entries.clear(); } } - let cell = Arc::new(OnceCell::new()); - entries.insert(host.to_owned(), Arc::clone(&cell)); - cell + let entry = self.start_lookup(host); + entries.insert(host.to_owned(), entry.clone()); + entry + } + + /// Run the blocking lookup on its own thread, which publishes the answer + /// itself: waiters from other sessions depend on it, so it must not be + /// abandoned when the caller that started it is cancelled or its runtime + /// shuts down. + fn start_lookup(&self, host: &str) -> Entry { + let (tx, rx) = watch::channel(None); + let tx = Arc::new(tx); + let thread_tx = Arc::clone(&tx); + let lookup = Arc::clone(&self.lookup); + let host = host.to_owned(); + let spawned = std::thread::Builder::new() + .name("dbx-sql-kernel-dns".to_owned()) + .spawn(move || { + let result = lookup(&host).and_then(|addrs| { + if addrs.is_empty() { + Err(io::Error::new( + io::ErrorKind::NotFound, + "DNS lookup returned no addresses", + )) + } else { + Ok(addrs) + } + }); + thread_tx.send_replace(Some(( + result.map(Arc::from).map_err(Arc::new), + Instant::now(), + ))); + }); + if let Err(e) = spawned { + tx.send_replace(Some((Err(Arc::new(e)), Instant::now()))); + } + rx } } impl Resolve for CachingResolver { fn resolve(&self, name: Name) -> Resolving { - let host = name.as_str().to_owned(); - let cell = self.entry(&host); - let lookup = Arc::clone(&self.lookup); + let mut entry = self.entry(name.as_str()); + let start = self.next.fetch_add(1, Ordering::Relaxed); Box::pin(async move { - let (answer, _) = cell.get_or_init(|| run_lookup(lookup, host)).await; - match answer { - Ok(addrs) => { - let addrs = Arc::clone(addrs); - Ok(Box::new((0..addrs.len()).map(move |i| addrs[i])) as Addrs) - } - Err(e) => Err(io::Error::new(e.kind(), e.to_string()).into()), + let result = match entry.wait_for(Option::is_some).await { + Ok(answer) => answer.as_ref().map(|(result, _)| result.clone()), + Err(_) => None, + }; + match result { + Some(Ok(addrs)) => Ok(Box::new(rotated(addrs, start)) as Addrs), + Some(Err(e)) => Err(io::Error::new(e.kind(), e.to_string()).into()), + None => Err(io::Error::other("DNS lookup thread exited").into()), } }) } } -/// Run the blocking lookup on its own thread, not the caller's blocking -/// pool: other sessions wait on this answer, so it must not be cancelled -/// when the session that started it shuts its runtime down. -async fn run_lookup(lookup: Lookup, host: String) -> Answer { - let (tx, rx) = tokio::sync::oneshot::channel(); - let spawned = std::thread::Builder::new() - .name("dbx-sql-kernel-dns".to_owned()) - .spawn(move || { - let _ = tx.send(lookup(&host)); - }); - let result = match spawned { - Err(e) => Err(e), - Ok(_) => match rx.await { - Ok(Ok(addrs)) if addrs.is_empty() => Err(io::Error::new( - io::ErrorKind::NotFound, - "DNS lookup returned no addresses", - )), - Ok(result) => result, - Err(_) => Err(io::Error::other("DNS lookup thread exited")), - }, - }; - (result.map(Arc::from).map_err(Arc::new), Instant::now()) +/// `addrs` starting at a different address per call. Only the leading run +/// of one address family rotates, so the family the connector tries first +/// (happy eyeballs) stays the resolver's choice. +fn rotated(addrs: Arc<[SocketAddr]>, start: usize) -> impl Iterator + Send { + let lead = addrs + .iter() + .take_while(|a| a.is_ipv4() == addrs[0].is_ipv4()) + .count(); + let offset = start % lead.max(1); + (0..addrs.len()).map(move |i| { + if i < lead { + addrs[(i + offset) % lead] + } else { + addrs[i] + } + }) } fn system_lookup(host: &str) -> io::Result> { @@ -249,6 +287,37 @@ mod tests { .build() .unwrap(); assert!(second.block_on(resolve(&r, "example.com")).is_ok()); - assert!(calls.load(Ordering::SeqCst) <= 2); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn lookup_survives_a_cancelled_caller() { + let (lookup, calls) = counting(Duration::from_millis(100), false); + let r = Arc::new(CachingResolver::new(TTL, lookup)); + let timed_out = + tokio::time::timeout(Duration::from_millis(10), resolve(&r, "example.com")).await; + assert!(timed_out.is_err(), "first caller is cancelled mid-lookup"); + resolve(&r, "example.com").await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn each_call_starts_at_the_next_address_of_the_leading_family() { + let lookup: Lookup = Arc::new(|_| { + Ok(["10.0.0.1:0", "10.0.0.2:0", "10.0.0.3:0", "[::1]:0"] + .iter() + .map(|a| a.parse().unwrap()) + .collect()) + }); + let r = Arc::new(CachingResolver::new(TTL, lookup)); + let mut firsts = std::collections::HashSet::new(); + for _ in 0..3 { + let addrs = resolve(&r, "example.com").await.unwrap(); + assert_eq!(addrs.len(), 4); + assert!(addrs[..3].iter().all(SocketAddr::is_ipv4)); + assert_eq!(addrs[3], "[::1]:0".parse().unwrap()); + firsts.insert(addrs[0]); + } + assert_eq!(firsts.len(), 3); } } From 1198c8210e498afdf85f2b22721de0e916bb6f3d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 19:36:25 +0000 Subject: [PATCH 03/12] fix(client): don't hold new callers on a stalled DNS lookup Callers that arrive more than 1 s after an unanswered lookup started begin a fresh one instead of joining it, so a single dropped query can't stall every new connection for glibc's 5 s retry. Document that answers are not invalidated on connect failure. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 90 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 70 insertions(+), 20 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index d89f42ab..6b6d22ca 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -21,7 +21,13 @@ //! its 5 s timeout), so a share of the opens stall for 5 s or more. This //! resolver runs one lookup per host at a time for the whole process and //! reuses a successful answer for [`TTL`]. Failures are shared with the -//! callers already waiting on that lookup but are not cached. +//! callers already waiting on that lookup but are not cached. A lookup still +//! unanswered after [`HEDGE`] is no longer joined: the next caller starts a +//! fresh one, so one dropped query can't hold every new connection. +//! +//! The answer is not invalidated when connecting to it fails, so after a +//! host moves to new addresses, new connections in this process may try the +//! old ones for up to [`TTL`] (the JVM's default caches the same way). use std::collections::HashMap; use std::io; @@ -36,6 +42,9 @@ use tokio::sync::watch; /// How long a successful answer is reused. Matches the JVM's default /// positive-lookup TTL, so the JDBC driver's behaviour is the reference. const TTL: Duration = Duration::from_secs(30); +/// How long new callers join an unanswered lookup before starting another; +/// well under glibc's 5 s retry timeout. +const HEDGE: Duration = Duration::from_secs(1); /// Bound on distinct cached hosts (workspace + CloudFetch storage hosts). const MAX_HOSTS: usize = 256; @@ -45,8 +54,10 @@ type Answer = (Result, Arc>, Instant); type Entry = watch::Receiver>; pub(crate) struct CachingResolver { - entries: Mutex>, + /// Each host's latest lookup and when it started. + entries: Mutex>, ttl: Duration, + hedge: Duration, lookup: Lookup, /// Rotates the first address handed out, as round-robin DNS would. next: AtomicUsize, @@ -57,45 +68,46 @@ impl CachingResolver { pub(crate) fn shared() -> Arc { static SHARED: OnceLock> = OnceLock::new(); SHARED - .get_or_init(|| Arc::new(Self::new(TTL, Arc::new(system_lookup)))) + .get_or_init(|| Arc::new(Self::new(TTL, HEDGE, Arc::new(system_lookup)))) .clone() } - fn new(ttl: Duration, lookup: Lookup) -> Self { + fn new(ttl: Duration, hedge: Duration, lookup: Lookup) -> Self { Self { entries: Mutex::new(HashMap::new()), ttl, + hedge, lookup, next: AtomicUsize::new(0), } } - /// The lookup to join for `host`: the one in flight, a fresh cached - /// answer, or a new lookup when the last one expired or failed. + /// The lookup to join for `host`: a recent one in flight, a fresh cached + /// answer, or a new lookup when the last one expired, failed or stalled. fn entry(&self, host: &str) -> Entry { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); - let usable = |entry: &Entry| { + let usable = |(entry, started): &(Entry, Instant)| { let in_flight = match &*entry.borrow() { None => true, Some((Ok(_), at)) => return at.elapsed() < self.ttl, Some((Err(_), _)) => return false, }; // An unanswered entry whose thread is gone will never be answered. - in_flight && entry.has_changed().is_ok() + in_flight && started.elapsed() < self.hedge && entry.has_changed().is_ok() }; - if let Some(entry) = entries.get(host) { - if usable(entry) { - return entry.clone(); + if let Some(current) = entries.get(host) { + if usable(current) { + return current.0.clone(); } } if entries.len() >= MAX_HOSTS { - entries.retain(|_, entry| usable(entry)); + entries.retain(|_, current| usable(current)); if entries.len() >= MAX_HOSTS { entries.clear(); } } let entry = self.start_lookup(host); - entries.insert(host.to_owned(), entry.clone()); + entries.insert(host.to_owned(), (entry.clone(), Instant::now())); entry } @@ -205,7 +217,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn concurrent_lookups_for_one_host_share_one_query() { let (lookup, calls) = counting(Duration::from_millis(50), false); - let r = Arc::new(CachingResolver::new(TTL, lookup)); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); let tasks: Vec<_> = (0..64) .map(|_| { let r = Arc::clone(&r); @@ -232,7 +244,11 @@ mod tests { #[tokio::test] async fn expired_answers_are_looked_up_again() { let (lookup, calls) = counting(Duration::ZERO, false); - let r = Arc::new(CachingResolver::new(Duration::from_millis(20), lookup)); + let r = Arc::new(CachingResolver::new( + Duration::from_millis(20), + HEDGE, + lookup, + )); resolve(&r, "example.com").await.unwrap(); tokio::time::sleep(Duration::from_millis(40)).await; resolve(&r, "example.com").await.unwrap(); @@ -242,7 +258,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn failures_reach_current_waiters_but_are_not_cached() { let (lookup, calls) = counting(Duration::from_millis(50), true); - let r = Arc::new(CachingResolver::new(TTL, lookup)); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); let tasks: Vec<_> = (0..16) .map(|_| { let r = Arc::clone(&r); @@ -264,14 +280,14 @@ mod tests { #[tokio::test] async fn empty_answers_are_errors() { let lookup: Lookup = Arc::new(|_| Ok(Vec::new())); - let r = Arc::new(CachingResolver::new(TTL, lookup)); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); assert!(resolve(&r, "example.com").await.is_err()); } #[test] fn lookup_survives_the_runtime_that_started_it() { let (lookup, calls) = counting(Duration::from_millis(100), false); - let r = Arc::new(CachingResolver::new(TTL, lookup)); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); let first = tokio::runtime::Builder::new_multi_thread() .worker_threads(1) .enable_all() @@ -293,7 +309,7 @@ mod tests { #[tokio::test] async fn lookup_survives_a_cancelled_caller() { let (lookup, calls) = counting(Duration::from_millis(100), false); - let r = Arc::new(CachingResolver::new(TTL, lookup)); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); let timed_out = tokio::time::timeout(Duration::from_millis(10), resolve(&r, "example.com")).await; assert!(timed_out.is_err(), "first caller is cancelled mid-lookup"); @@ -309,7 +325,7 @@ mod tests { .map(|a| a.parse().unwrap()) .collect()) }); - let r = Arc::new(CachingResolver::new(TTL, lookup)); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); let mut firsts = std::collections::HashSet::new(); for _ in 0..3 { let addrs = resolve(&r, "example.com").await.unwrap(); @@ -320,4 +336,38 @@ mod tests { } assert_eq!(firsts.len(), 3); } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn callers_after_the_hedge_window_start_a_new_lookup() { + let calls = Arc::new(AtomicUsize::new(0)); + let c = Arc::clone(&calls); + let lookup: Lookup = Arc::new(move |_| { + // The first query stalls (a dropped packet); the retry is fast. + if c.fetch_add(1, Ordering::SeqCst) == 0 { + std::thread::sleep(Duration::from_millis(500)); + } + Ok(vec!["10.0.0.1:0".parse().unwrap()]) + }); + let r = Arc::new(CachingResolver::new(TTL, Duration::from_millis(50), lookup)); + let r1 = Arc::clone(&r); + let early = tokio::spawn(async move { resolve(&r1, "example.com").await }); + tokio::time::sleep(Duration::from_millis(20)).await; + let joined = Instant::now(); + let r2 = Arc::clone(&r); + let within_window = tokio::spawn(async move { resolve(&r2, "example.com").await }); + tokio::time::sleep(Duration::from_millis(80)).await; + let started = Instant::now(); + resolve(&r, "example.com").await.unwrap(); + assert!( + started.elapsed() < Duration::from_millis(300), + "not held by the stall" + ); + assert_eq!(calls.load(Ordering::SeqCst), 2); + within_window.await.unwrap().unwrap(); + assert!( + joined.elapsed() >= Duration::from_millis(400), + "joined the first lookup" + ); + early.await.unwrap().unwrap(); + } } From a9d8770b7dbd14b9cd94a6c28d132ee0195f5392 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 19:51:28 +0000 Subject: [PATCH 04/12] docs(client): note that the DNS cache ignores the record's own TTL Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index 6b6d22ca..7cc957cc 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -25,9 +25,11 @@ //! unanswered after [`HEDGE`] is no longer joined: the next caller starts a //! fresh one, so one dropped query can't hold every new connection. //! -//! The answer is not invalidated when connecting to it fails, so after a -//! host moves to new addresses, new connections in this process may try the -//! old ones for up to [`TTL`] (the JVM's default caches the same way). +//! [`TTL`] is fixed: `getaddrinfo` doesn't report the record's own DNS TTL, +//! so that is ignored. The answer is also not invalidated when connecting to +//! it fails, so after a host moves to new addresses, new connections in this +//! process may try the old ones for up to [`TTL`] (the JVM's default caches +//! the same way). use std::collections::HashMap; use std::io; From 8a078f9cec2f64d16f25179de737c6089d19b7a7 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 00:38:56 +0000 Subject: [PATCH 05/12] fix(client): answer callers already waiting on a stalled DNS lookup The hedge started a new lookup only for callers arriving after the window, so the callers already joined to a dropped query, most of a burst, still waited for glibc's 5 s retry. Each lookup now runs on a coordinating thread that starts another attempt every HEDGE while none has answered (up to MAX_ATTEMPTS) and publishes the first answer to everyone waiting on it. The hedge tests block the stalled attempt until released instead of relying on sleeps. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 4 +- src/client/dns.rs | 196 ++++++++++++++++++++++++++++++++-------------- 2 files changed, 142 insertions(+), 58 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8469524b..534d51f4 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,7 +22,9 @@ changes go in their respective binding's NEXT_CHANGELOG. `adbc.databricks.http.headers` is now rejected; use the dedicated entry option. - All HTTP clients in a process share one DNS lookup per host at a time and reuse a successful answer for 30 s, so many sessions opening at once no - longer send one identical lookup each. + longer send one identical lookup each. A lookup still unanswered after 1 s + is tried again alongside (up to 3 attempts), and every waiting session gets + the first answer. ### Updated diff --git a/src/client/dns.rs b/src/client/dns.rs index 7cc957cc..10fac54d 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -22,8 +22,9 @@ //! resolver runs one lookup per host at a time for the whole process and //! reuses a successful answer for [`TTL`]. Failures are shared with the //! callers already waiting on that lookup but are not cached. A lookup still -//! unanswered after [`HEDGE`] is no longer joined: the next caller starts a -//! fresh one, so one dropped query can't hold every new connection. +//! unanswered after [`HEDGE`] gets another attempt, up to [`MAX_ATTEMPTS`], +//! and the first answer reaches every caller waiting on it, so one dropped +//! query doesn't hold the whole burst for glibc's retry. //! //! [`TTL`] is fixed: `getaddrinfo` doesn't report the record's own DNS TTL, //! so that is ignored. The answer is also not invalidated when connecting to @@ -44,9 +45,11 @@ use tokio::sync::watch; /// How long a successful answer is reused. Matches the JVM's default /// positive-lookup TTL, so the JDBC driver's behaviour is the reference. const TTL: Duration = Duration::from_secs(30); -/// How long new callers join an unanswered lookup before starting another; -/// well under glibc's 5 s retry timeout. +/// How long a lookup goes unanswered before another attempt starts; well +/// under glibc's 5 s retry timeout. const HEDGE: Duration = Duration::from_secs(1); +/// Attempts per lookup, started [`HEDGE`] apart while none has answered. +const MAX_ATTEMPTS: usize = 3; /// Bound on distinct cached hosts (workspace + CloudFetch storage hosts). const MAX_HOSTS: usize = 256; @@ -56,8 +59,8 @@ type Answer = (Result, Arc>, Instant); type Entry = watch::Receiver>; pub(crate) struct CachingResolver { - /// Each host's latest lookup and when it started. - entries: Mutex>, + /// Each host's latest lookup. + entries: Mutex>, ttl: Duration, hedge: Duration, lookup: Lookup, @@ -84,22 +87,19 @@ impl CachingResolver { } } - /// The lookup to join for `host`: a recent one in flight, a fresh cached - /// answer, or a new lookup when the last one expired, failed or stalled. + /// The lookup to join for `host`: one in flight, a fresh cached answer, or + /// a new lookup when the last one expired or failed. fn entry(&self, host: &str) -> Entry { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); - let usable = |(entry, started): &(Entry, Instant)| { - let in_flight = match &*entry.borrow() { - None => true, - Some((Ok(_), at)) => return at.elapsed() < self.ttl, - Some((Err(_), _)) => return false, - }; + let usable = |entry: &Entry| match &*entry.borrow() { // An unanswered entry whose thread is gone will never be answered. - in_flight && started.elapsed() < self.hedge && entry.has_changed().is_ok() + None => entry.has_changed().is_ok(), + Some((Ok(_), at)) => at.elapsed() < self.ttl, + Some((Err(_), _)) => false, }; if let Some(current) = entries.get(host) { if usable(current) { - return current.0.clone(); + return current.clone(); } } if entries.len() >= MAX_HOSTS { @@ -109,24 +109,74 @@ impl CachingResolver { } } let entry = self.start_lookup(host); - entries.insert(host.to_owned(), (entry.clone(), Instant::now())); + entries.insert(host.to_owned(), entry.clone()); entry } - /// Run the blocking lookup on its own thread, which publishes the answer - /// itself: waiters from other sessions depend on it, so it must not be - /// abandoned when the caller that started it is cancelled or its runtime - /// shuts down. + /// Run the lookup off the caller's runtime on a thread that publishes the + /// answer itself: waiters from other sessions depend on it, so it must not + /// be abandoned when the caller that started it is cancelled or its + /// runtime shuts down. While no attempt has answered, another starts every + /// `hedge`, and the first answer is published. fn start_lookup(&self, host: &str) -> Entry { let (tx, rx) = watch::channel(None); - let tx = Arc::new(tx); - let thread_tx = Arc::clone(&tx); let lookup = Arc::clone(&self.lookup); + let hedge = self.hedge; let host = host.to_owned(); let spawned = std::thread::Builder::new() .name("dbx-sql-kernel-dns".to_owned()) .spawn(move || { - let result = lookup(&host).and_then(|addrs| { + let result = first_answer(&lookup, &host, hedge); + tx.send_replace(Some(( + result.map(Arc::from).map_err(Arc::new), + Instant::now(), + ))); + }); + match spawned { + Ok(_) => rx, + Err(e) => { + let (tx, rx) = watch::channel(None); + tx.send_replace(Some((Err(Arc::new(e)), Instant::now()))); + rx + } + } + } +} + +/// The first answer from up to [`MAX_ATTEMPTS`] attempts at `lookup(host)`, +/// each on its own thread, started `hedge` apart while none has answered. +fn first_answer(lookup: &Lookup, host: &str, hedge: Duration) -> io::Result> { + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let mut done_tx = Some(done_tx); + let mut attempts = 0; + let mut spawn_error = None; + loop { + if let Some(sender) = done_tx.as_ref() { + let (sender, lookup, host) = (sender.clone(), Arc::clone(lookup), host.to_owned()); + attempts += 1; + let spawned = std::thread::Builder::new() + .name("dbx-sql-kernel-dns".to_owned()) + .spawn(move || { + let _ = sender.send(lookup(&host)); + }); + if let Err(e) = spawned { + spawn_error = Some(e); + done_tx = None; + } else if attempts == MAX_ATTEMPTS { + // No more attempts: let the channel close once they all end. + done_tx = None; + } + } + let received = if done_tx.is_some() { + done_rx.recv_timeout(hedge) + } else { + done_rx + .recv() + .map_err(|_| std::sync::mpsc::RecvTimeoutError::Disconnected) + }; + match received { + Ok(result) => { + return result.and_then(|addrs| { if addrs.is_empty() { Err(io::Error::new( io::ErrorKind::NotFound, @@ -136,15 +186,14 @@ impl CachingResolver { Ok(addrs) } }); - thread_tx.send_replace(Some(( - result.map(Arc::from).map_err(Arc::new), - Instant::now(), - ))); - }); - if let Err(e) = spawned { - tx.send_replace(Some((Err(Arc::new(e)), Instant::now()))); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + return Err( + spawn_error.unwrap_or_else(|| io::Error::other("DNS lookup threads exited")) + ); + } } - rx } } @@ -339,37 +388,70 @@ mod tests { assert_eq!(firsts.len(), 3); } - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn callers_after_the_hedge_window_start_a_new_lookup() { + type Release = Arc<(Mutex, std::sync::Condvar)>; + + /// A lookup whose first `stalled` attempts block until released, like a + /// dropped query waiting for glibc's retry; later attempts answer at once. + fn stalling(stalled: usize) -> (Lookup, Arc, Release) { let calls = Arc::new(AtomicUsize::new(0)); - let c = Arc::clone(&calls); + let release: Release = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let (c, rel) = (Arc::clone(&calls), Arc::clone(&release)); let lookup: Lookup = Arc::new(move |_| { - // The first query stalls (a dropped packet); the retry is fast. - if c.fetch_add(1, Ordering::SeqCst) == 0 { - std::thread::sleep(Duration::from_millis(500)); + if c.fetch_add(1, Ordering::SeqCst) < stalled { + let (released, wake) = &*rel; + let _released = wake + .wait_while(released.lock().unwrap(), |done| !*done) + .unwrap(); } Ok(vec!["10.0.0.1:0".parse().unwrap()]) }); + (lookup, calls, release) + } + + fn release(stall: &Release) { + *stall.0.lock().unwrap() = true; + stall.1.notify_all(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn callers_waiting_on_a_stalled_lookup_get_the_hedged_answer() { + // The first query never answers on its own; everyone already waiting + // on it is answered by the second attempt. + let (lookup, calls, stall) = stalling(1); let r = Arc::new(CachingResolver::new(TTL, Duration::from_millis(50), lookup)); - let r1 = Arc::clone(&r); - let early = tokio::spawn(async move { resolve(&r1, "example.com").await }); - tokio::time::sleep(Duration::from_millis(20)).await; - let joined = Instant::now(); - let r2 = Arc::clone(&r); - let within_window = tokio::spawn(async move { resolve(&r2, "example.com").await }); - tokio::time::sleep(Duration::from_millis(80)).await; - let started = Instant::now(); - resolve(&r, "example.com").await.unwrap(); - assert!( - started.elapsed() < Duration::from_millis(300), - "not held by the stall" - ); + let waiters: Vec<_> = (0..8) + .map(|_| { + let r = Arc::clone(&r); + tokio::spawn(async move { resolve(&r, "example.com").await }) + }) + .collect(); + for waiter in waiters { + let addrs = tokio::time::timeout(Duration::from_secs(10), waiter) + .await + .expect("held by the stalled query") + .unwrap() + .unwrap(); + assert_eq!(addrs, vec!["10.0.0.1:0".parse().unwrap()]); + } assert_eq!(calls.load(Ordering::SeqCst), 2); - within_window.await.unwrap().unwrap(); - assert!( - joined.elapsed() >= Duration::from_millis(400), - "joined the first lookup" - ); - early.await.unwrap().unwrap(); + release(&stall); + } + + #[tokio::test] + async fn a_lookup_makes_at_most_max_attempts() { + let (lookup, calls, stall) = stalling(usize::MAX); + let r = Arc::new(CachingResolver::new(TTL, Duration::from_millis(10), lookup)); + let r1 = Arc::clone(&r); + let pending = tokio::spawn(async move { resolve(&r1, "example.com").await }); + let deadline = Instant::now() + Duration::from_secs(10); + while calls.load(Ordering::SeqCst) < MAX_ATTEMPTS { + assert!(Instant::now() < deadline, "attempts didn't start"); + tokio::time::sleep(Duration::from_millis(5)).await; + } + // Ten more hedge intervals pass without another attempt. + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(calls.load(Ordering::SeqCst), MAX_ATTEMPTS); + release(&stall); + pending.await.unwrap().unwrap(); } } From c5b9cbb7139a16379dffc3a7d7d154ff8f2e60b4 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 00:53:04 +0000 Subject: [PATCH 06/12] fix(client): let the first successful DNS attempt win; expire orphaned lookups The first attempt to answer was published even when it was an error, so a fast EAI_AGAIN from an overloaded stub could fail every waiting session while another attempt would have succeeded. A failed attempt now starts the next one at once, and the error is returned only when every attempt failed. Attempt threads catch panics so each one reports back. An unanswered entry older than 60 s is replaced: after fork() the child inherits in-flight entries whose lookup threads don't exist there. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 6 +- src/client/dns.rs | 162 ++++++++++++++++++++++++++++++++-------------- 2 files changed, 115 insertions(+), 53 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 534d51f4..ce8f4d7d 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,9 +22,9 @@ changes go in their respective binding's NEXT_CHANGELOG. `adbc.databricks.http.headers` is now rejected; use the dedicated entry option. - All HTTP clients in a process share one DNS lookup per host at a time and reuse a successful answer for 30 s, so many sessions opening at once no - longer send one identical lookup each. A lookup still unanswered after 1 s - is tried again alongside (up to 3 attempts), and every waiting session gets - the first answer. + longer send one identical lookup each. A lookup that hasn't succeeded after + 1 s, or that failed, is tried again alongside (up to 3 attempts), and every + waiting session gets the first successful answer. ### Updated diff --git a/src/client/dns.rs b/src/client/dns.rs index 10fac54d..e835ed50 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -48,8 +48,13 @@ const TTL: Duration = Duration::from_secs(30); /// How long a lookup goes unanswered before another attempt starts; well /// under glibc's 5 s retry timeout. const HEDGE: Duration = Duration::from_secs(1); -/// Attempts per lookup, started [`HEDGE`] apart while none has answered. +/// Attempts per lookup, started [`HEDGE`] apart while none has succeeded +/// (or at once when one fails). const MAX_ATTEMPTS: usize = 3; +/// An unanswered lookup older than this is replaced. A lookup's own threads +/// always answer well before; this covers an entry inherited across `fork()`, +/// whose threads don't exist in the child. +const STUCK_AFTER: Duration = Duration::from_secs(60); /// Bound on distinct cached hosts (workspace + CloudFetch storage hosts). const MAX_HOSTS: usize = 256; @@ -59,8 +64,8 @@ type Answer = (Result, Arc>, Instant); type Entry = watch::Receiver>; pub(crate) struct CachingResolver { - /// Each host's latest lookup. - entries: Mutex>, + /// Each host's latest lookup and when it started. + entries: Mutex>, ttl: Duration, hedge: Duration, lookup: Lookup, @@ -91,15 +96,15 @@ impl CachingResolver { /// a new lookup when the last one expired or failed. fn entry(&self, host: &str) -> Entry { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); - let usable = |entry: &Entry| match &*entry.borrow() { + let usable = |(entry, started): &(Entry, Instant)| match &*entry.borrow() { // An unanswered entry whose thread is gone will never be answered. - None => entry.has_changed().is_ok(), + None => entry.has_changed().is_ok() && started.elapsed() < STUCK_AFTER, Some((Ok(_), at)) => at.elapsed() < self.ttl, Some((Err(_), _)) => false, }; if let Some(current) = entries.get(host) { if usable(current) { - return current.clone(); + return current.0.clone(); } } if entries.len() >= MAX_HOSTS { @@ -109,15 +114,14 @@ impl CachingResolver { } } let entry = self.start_lookup(host); - entries.insert(host.to_owned(), entry.clone()); + entries.insert(host.to_owned(), (entry.clone(), Instant::now())); entry } /// Run the lookup off the caller's runtime on a thread that publishes the /// answer itself: waiters from other sessions depend on it, so it must not /// be abandoned when the caller that started it is cancelled or its - /// runtime shuts down. While no attempt has answered, another starts every - /// `hedge`, and the first answer is published. + /// runtime shuts down. See [`first_answer`] for how attempts are made. fn start_lookup(&self, host: &str) -> Entry { let (tx, rx) = watch::channel(None); let lookup = Arc::clone(&self.lookup); @@ -143,56 +147,53 @@ impl CachingResolver { } } -/// The first answer from up to [`MAX_ATTEMPTS`] attempts at `lookup(host)`, -/// each on its own thread, started `hedge` apart while none has answered. +/// The first successful answer from up to [`MAX_ATTEMPTS`] attempts at +/// `lookup(host)`, each on its own thread. Another attempt starts every +/// `hedge` while none has succeeded, and at once when one fails: a fast +/// failure (`EAI_AGAIN` from an overloaded stub) must not fail every waiter +/// while another attempt may still succeed. The last error is returned only +/// once every attempt has failed. fn first_answer(lookup: &Lookup, host: &str, hedge: Duration) -> io::Result> { let (done_tx, done_rx) = std::sync::mpsc::channel(); - let mut done_tx = Some(done_tx); - let mut attempts = 0; - let mut spawn_error = None; + let (mut attempts, mut running) = (0, 0); + let mut last_error = None; + // Each pass starts an attempt while under the cap: the first, then one + // per `hedge` without a success, or one right after a failure. loop { - if let Some(sender) = done_tx.as_ref() { - let (sender, lookup, host) = (sender.clone(), Arc::clone(lookup), host.to_owned()); + if attempts < MAX_ATTEMPTS { attempts += 1; + let (sender, lookup, host) = (done_tx.clone(), Arc::clone(lookup), host.to_owned()); let spawned = std::thread::Builder::new() .name("dbx-sql-kernel-dns".to_owned()) .spawn(move || { - let _ = sender.send(lookup(&host)); + // Always report back, so the attempt is never waited on forever. + let result = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| lookup(&host))) + .unwrap_or_else(|_| Err(io::Error::other("DNS lookup panicked"))); + let _ = sender.send(result); }); - if let Err(e) = spawned { - spawn_error = Some(e); - done_tx = None; - } else if attempts == MAX_ATTEMPTS { - // No more attempts: let the channel close once they all end. - done_tx = None; + match spawned { + Ok(_) => running += 1, + Err(e) => last_error = Some(e), } } - let received = if done_tx.is_some() { - done_rx.recv_timeout(hedge) - } else { - done_rx - .recv() - .map_err(|_| std::sync::mpsc::RecvTimeoutError::Disconnected) - }; - match received { - Ok(result) => { - return result.and_then(|addrs| { - if addrs.is_empty() { - Err(io::Error::new( - io::ErrorKind::NotFound, - "DNS lookup returned no addresses", - )) - } else { - Ok(addrs) - } - }); + if running == 0 { + if attempts < MAX_ATTEMPTS { + continue; } - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { - return Err( - spawn_error.unwrap_or_else(|| io::Error::other("DNS lookup threads exited")) - ); + return Err(last_error.unwrap_or_else(|| io::Error::other("DNS lookup failed"))); + } + match done_rx.recv_timeout(hedge) { + Ok(Ok(addrs)) if !addrs.is_empty() => return Ok(addrs), + Ok(result) => { + running -= 1; + last_error = Some(result.err().unwrap_or_else(|| { + io::Error::new(io::ErrorKind::NotFound, "DNS lookup returned no addresses") + })); } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + // The coordinator holds a sender, so the channel can't close. + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => unreachable!(), } } } @@ -319,15 +320,71 @@ mod tests { for t in tasks { assert!(t.await.unwrap().unwrap_err().contains("boom")); } - assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!( + calls.load(Ordering::SeqCst), + MAX_ATTEMPTS, + "every attempt failed" + ); assert!(resolve(&r, "example.com").await.is_err()); assert_eq!( calls.load(Ordering::SeqCst), - 2, + 2 * MAX_ATTEMPTS, "a failure is retried by the next caller" ); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_fast_failure_does_not_beat_an_attempt_that_succeeds() { + // The first attempt fails at once (EAI_AGAIN from an overloaded + // stub); the next one answers, and that is what every waiter gets. + let calls = Arc::new(AtomicUsize::new(0)); + let c = Arc::clone(&calls); + let lookup: Lookup = Arc::new(move |_| { + if c.fetch_add(1, Ordering::SeqCst) == 0 { + Err(io::Error::other("Temporary failure in name resolution")) + } else { + Ok(vec!["10.0.0.1:0".parse().unwrap()]) + } + }); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); + let tasks: Vec<_> = (0..8) + .map(|_| { + let r = Arc::clone(&r); + tokio::spawn(async move { resolve(&r, "example.com").await }) + }) + .collect(); + for t in tasks { + assert_eq!( + t.await.unwrap().unwrap(), + vec!["10.0.0.1:0".parse().unwrap()] + ); + } + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn an_unanswered_entry_past_its_deadline_is_replaced() { + // After fork() the child keeps an in-flight entry whose lookup + // threads (and their senders' owners) don't exist there. + let (lookup, calls) = counting(Duration::ZERO, false); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); + let (orphan_tx, orphan_rx) = watch::channel(None); + let long_ago = Instant::now() + .checked_sub(STUCK_AFTER + Duration::from_secs(1)) + .expect("monotonic clock far enough from its origin"); + r.entries + .lock() + .unwrap() + .insert("example.com".to_owned(), (orphan_rx, long_ago)); + let addrs = tokio::time::timeout(Duration::from_secs(10), resolve(&r, "example.com")) + .await + .expect("waited on the orphaned entry") + .unwrap(); + assert_eq!(addrs, vec!["10.0.0.1:0".parse().unwrap()]); + assert_eq!(calls.load(Ordering::SeqCst), 1); + drop(orphan_tx); + } + #[tokio::test] async fn empty_answers_are_errors() { let lookup: Lookup = Arc::new(|_| Ok(Vec::new())); @@ -346,7 +403,12 @@ mod tests { .unwrap(); let r1 = Arc::clone(&r); first.spawn(async move { resolve(&r1, "example.com").await }); - std::thread::sleep(Duration::from_millis(20)); + // Shut down only once that task's lookup is running. + let deadline = Instant::now() + Duration::from_secs(10); + while calls.load(Ordering::SeqCst) == 0 { + assert!(Instant::now() < deadline, "the lookup never started"); + std::thread::sleep(Duration::from_millis(1)); + } first.shutdown_background(); let second = tokio::runtime::Builder::new_current_thread() From f93b19beaec17dd2cc3b9ead452f5657cdef3173 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 00:59:24 +0000 Subject: [PATCH 07/12] docs(client): the DNS module doc says the first successful answer wins Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index e835ed50..5e6e1ec3 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -20,11 +20,11 @@ //! stub resolvers (systemd-resolved drops the excess and glibc retries after //! its 5 s timeout), so a share of the opens stall for 5 s or more. This //! resolver runs one lookup per host at a time for the whole process and -//! reuses a successful answer for [`TTL`]. Failures are shared with the -//! callers already waiting on that lookup but are not cached. A lookup still -//! unanswered after [`HEDGE`] gets another attempt, up to [`MAX_ATTEMPTS`], -//! and the first answer reaches every caller waiting on it, so one dropped -//! query doesn't hold the whole burst for glibc's retry. +//! reuses a successful answer for [`TTL`]. A lookup that hasn't succeeded +//! after [`HEDGE`], or whose attempt failed, gets another attempt, up to +//! [`MAX_ATTEMPTS`]. The first successful answer reaches every caller waiting +//! on it, so one dropped query doesn't hold the whole burst for glibc's retry. +//! An error reaches them only when every attempt failed, and is not cached. //! //! [`TTL`] is fixed: `getaddrinfo` doesn't report the record's own DNS TTL, //! so that is ignored. The answer is also not invalidated when connecting to From 9f96c07d2d4f21cd6b4267d504e76cf78d30ee6a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 01:15:42 +0000 Subject: [PATCH 08/12] test(client): let the hedge tests tolerate a third attempt On a loaded runner the coordinator can start another attempt before the second one reports back. What the tests check is that waiters get the successful answer; the attempt count only has to stay within the cap. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index 5e6e1ec3..6d02160a 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -359,7 +359,8 @@ mod tests { vec!["10.0.0.1:0".parse().unwrap()] ); } - assert_eq!(calls.load(Ordering::SeqCst), 2); + // A slow scheduler may let another hedge start before the answer arrives. + assert!((2..=MAX_ATTEMPTS).contains(&calls.load(Ordering::SeqCst))); } #[tokio::test] @@ -495,7 +496,8 @@ mod tests { .unwrap(); assert_eq!(addrs, vec!["10.0.0.1:0".parse().unwrap()]); } - assert_eq!(calls.load(Ordering::SeqCst), 2); + // A slow scheduler may let another hedge start before the answer arrives. + assert!((2..=MAX_ATTEMPTS).contains(&calls.load(Ordering::SeqCst))); release(&stall); } From f7195aa93ea24a0149c00867fec0c3b06dae7bf5 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 01:30:55 +0000 Subject: [PATCH 09/12] fix(client): reuse DNS failures briefly; replace lookups from a parent process A host that doesn't resolve got three attempts per lookup, and failures weren't reused, so retries from every session multiplied the load on the stub resolver this exists to protect. A failure is now reused for 2 s (the JVM caches negative lookups for 10 s by default). Each entry records the process that started it. After fork() the child replaces an inherited in-flight entry at once instead of after the 60 s backstop. The backstop and the negative TTL are fields, so the tests set short ones instead of depending on system uptime. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 120 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 91 insertions(+), 29 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index 6d02160a..126958db 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -24,7 +24,8 @@ //! after [`HEDGE`], or whose attempt failed, gets another attempt, up to //! [`MAX_ATTEMPTS`]. The first successful answer reaches every caller waiting //! on it, so one dropped query doesn't hold the whole burst for glibc's retry. -//! An error reaches them only when every attempt failed, and is not cached. +//! An error reaches them only when every attempt failed, and is reused for +//! [`NEGATIVE_TTL`]. //! //! [`TTL`] is fixed: `getaddrinfo` doesn't report the record's own DNS TTL, //! so that is ignored. The answer is also not invalidated when connecting to @@ -51,9 +52,13 @@ const HEDGE: Duration = Duration::from_secs(1); /// Attempts per lookup, started [`HEDGE`] apart while none has succeeded /// (or at once when one fails). const MAX_ATTEMPTS: usize = 3; -/// An unanswered lookup older than this is replaced. A lookup's own threads -/// always answer well before; this covers an entry inherited across `fork()`, -/// whose threads don't exist in the child. +/// How long a failed lookup is reused, so retries from every session against +/// a host that doesn't resolve make one lookup, not one each (the JVM's +/// default negative TTL is 10 s). +const NEGATIVE_TTL: Duration = Duration::from_secs(2); +/// An unanswered lookup older than this is replaced; a backstop for a lookup +/// that never returns. (One inherited across `fork()` is replaced at once, see +/// [`Slot::pid`].) const STUCK_AFTER: Duration = Duration::from_secs(60); /// Bound on distinct cached hosts (workspace + CloudFetch storage hosts). const MAX_HOSTS: usize = 256; @@ -63,10 +68,20 @@ type Answer = (Result, Arc>, Instant); /// `None` while the lookup thread runs; the thread publishes the answer. type Entry = watch::Receiver>; +/// A host's latest lookup. +struct Slot { + entry: Entry, + started: Instant, + /// The process that started it. A child after `fork()` has the entry but + /// not the lookup threads that would answer it. + pid: u32, +} + pub(crate) struct CachingResolver { - /// Each host's latest lookup and when it started. - entries: Mutex>, + entries: Mutex>, ttl: Duration, + negative_ttl: Duration, + stuck_after: Duration, hedge: Duration, lookup: Lookup, /// Rotates the first address handed out, as round-robin DNS would. @@ -86,25 +101,32 @@ impl CachingResolver { Self { entries: Mutex::new(HashMap::new()), ttl, + negative_ttl: NEGATIVE_TTL, + stuck_after: STUCK_AFTER, hedge, lookup, next: AtomicUsize::new(0), } } - /// The lookup to join for `host`: one in flight, a fresh cached answer, or - /// a new lookup when the last one expired or failed. + /// The lookup to join for `host`: one in flight, a recent answer, or a new + /// lookup when the last one expired. fn entry(&self, host: &str) -> Entry { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); - let usable = |(entry, started): &(Entry, Instant)| match &*entry.borrow() { - // An unanswered entry whose thread is gone will never be answered. - None => entry.has_changed().is_ok() && started.elapsed() < STUCK_AFTER, + let usable = |slot: &Slot| match &*slot.entry.borrow() { + // An unanswered entry is joined only while something can still + // answer it. + None => { + slot.entry.has_changed().is_ok() + && slot.pid == std::process::id() + && slot.started.elapsed() < self.stuck_after + } Some((Ok(_), at)) => at.elapsed() < self.ttl, - Some((Err(_), _)) => false, + Some((Err(_), at)) => at.elapsed() < self.negative_ttl, }; if let Some(current) = entries.get(host) { if usable(current) { - return current.0.clone(); + return current.entry.clone(); } } if entries.len() >= MAX_HOSTS { @@ -114,7 +136,12 @@ impl CachingResolver { } } let entry = self.start_lookup(host); - entries.insert(host.to_owned(), (entry.clone(), Instant::now())); + let slot = Slot { + entry: entry.clone(), + started: Instant::now(), + pid: std::process::id(), + }; + entries.insert(host.to_owned(), slot); entry } @@ -308,9 +335,11 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn failures_reach_current_waiters_but_are_not_cached() { + async fn failures_reach_current_waiters_and_are_reused_briefly() { let (lookup, calls) = counting(Duration::from_millis(50), true); - let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); + let mut r = CachingResolver::new(TTL, HEDGE, lookup); + r.negative_ttl = Duration::from_millis(200); + let r = Arc::new(r); let tasks: Vec<_> = (0..16) .map(|_| { let r = Arc::clone(&r); @@ -326,10 +355,17 @@ mod tests { "every attempt failed" ); assert!(resolve(&r, "example.com").await.is_err()); + assert_eq!( + calls.load(Ordering::SeqCst), + MAX_ATTEMPTS, + "a recent failure is reused" + ); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(resolve(&r, "example.com").await.is_err()); assert_eq!( calls.load(Ordering::SeqCst), 2 * MAX_ATTEMPTS, - "a failure is retried by the next caller" + "an expired failure is looked up again" ); } @@ -363,27 +399,53 @@ mod tests { assert!((2..=MAX_ATTEMPTS).contains(&calls.load(Ordering::SeqCst))); } - #[tokio::test] - async fn an_unanswered_entry_past_its_deadline_is_replaced() { - // After fork() the child keeps an in-flight entry whose lookup - // threads (and their senders' owners) don't exist there. - let (lookup, calls) = counting(Duration::ZERO, false); - let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); + /// An unanswered entry nothing will answer: its sender is kept alive, as + /// in a child after `fork()`, where the lookup threads don't exist. + fn insert_orphan( + r: &CachingResolver, + started: Instant, + pid: u32, + ) -> watch::Sender> { let (orphan_tx, orphan_rx) = watch::channel(None); - let long_ago = Instant::now() - .checked_sub(STUCK_AFTER + Duration::from_secs(1)) - .expect("monotonic clock far enough from its origin"); + let slot = Slot { + entry: orphan_rx, + started, + pid, + }; r.entries .lock() .unwrap() - .insert("example.com".to_owned(), (orphan_rx, long_ago)); - let addrs = tokio::time::timeout(Duration::from_secs(10), resolve(&r, "example.com")) + .insert("example.com".to_owned(), slot); + orphan_tx + } + + async fn resolves_with_one_new_lookup(r: &Arc, calls: &AtomicUsize) { + let addrs = tokio::time::timeout(Duration::from_secs(10), resolve(r, "example.com")) .await .expect("waited on the orphaned entry") .unwrap(); assert_eq!(addrs, vec!["10.0.0.1:0".parse().unwrap()]); assert_eq!(calls.load(Ordering::SeqCst), 1); - drop(orphan_tx); + } + + #[tokio::test] + async fn an_entry_from_another_process_is_replaced_at_once() { + let (lookup, calls) = counting(Duration::ZERO, false); + let r = Arc::new(CachingResolver::new(TTL, HEDGE, lookup)); + let parent = std::process::id().wrapping_add(1); + let _orphan = insert_orphan(&r, Instant::now(), parent); + resolves_with_one_new_lookup(&r, &calls).await; + } + + #[tokio::test] + async fn an_unanswered_entry_past_its_deadline_is_replaced() { + let (lookup, calls) = counting(Duration::ZERO, false); + let mut r = CachingResolver::new(TTL, HEDGE, lookup); + r.stuck_after = Duration::from_millis(20); + let r = Arc::new(r); + let _orphan = insert_orphan(&r, Instant::now(), std::process::id()); + tokio::time::sleep(Duration::from_millis(40)).await; + resolves_with_one_new_lookup(&r, &calls).await; } #[tokio::test] From 63dee365aa48c80364eaaa820cb2a68a7df4419d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 01:31:08 +0000 Subject: [PATCH 10/12] docs: note in NEXT_CHANGELOG that DNS failures are reused for 2 s Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ce8f4d7d..30322d3d 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -24,7 +24,8 @@ changes go in their respective binding's NEXT_CHANGELOG. reuse a successful answer for 30 s, so many sessions opening at once no longer send one identical lookup each. A lookup that hasn't succeeded after 1 s, or that failed, is tried again alongside (up to 3 attempts), and every - waiting session gets the first successful answer. + waiting session gets the first successful answer. A failure is reused for + 2 s. ### Updated From caa836319e617a3e0241add0e7b73c360879222a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 01:42:02 +0000 Subject: [PATCH 11/12] fix(client): settle a DNS lookup whose attempts all hang If every attempt blocked (getaddrinfo stuck on an unreachable nameserver), the coordinator never published, and the 60 s backstop started another coordinator and attempts beside the stuck ones each time. The coordinator now publishes TimedOut once that deadline passes, so waiters get an answer and the slot settles. A test also checks that DatabricksHttpClient actually resolves through the shared cache. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 47 +++++++++++++++++++++++++++++++++++++++++----- src/client/http.rs | 20 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index 126958db..c64af238 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -145,6 +145,15 @@ impl CachingResolver { entry } + /// Whether `host` has a cached successful answer (tests only). + #[cfg(test)] + pub(crate) fn has_answer(&self, host: &str) -> bool { + let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + entries + .get(host) + .is_some_and(|slot| matches!(&*slot.entry.borrow(), Some((Ok(_), _)))) + } + /// Run the lookup off the caller's runtime on a thread that publishes the /// answer itself: waiters from other sessions depend on it, so it must not /// be abandoned when the caller that started it is cancelled or its @@ -152,12 +161,12 @@ impl CachingResolver { fn start_lookup(&self, host: &str) -> Entry { let (tx, rx) = watch::channel(None); let lookup = Arc::clone(&self.lookup); - let hedge = self.hedge; + let (hedge, deadline) = (self.hedge, self.stuck_after); let host = host.to_owned(); let spawned = std::thread::Builder::new() .name("dbx-sql-kernel-dns".to_owned()) .spawn(move || { - let result = first_answer(&lookup, &host, hedge); + let result = first_answer(&lookup, &host, hedge, deadline); tx.send_replace(Some(( result.map(Arc::from).map_err(Arc::new), Instant::now(), @@ -179,8 +188,15 @@ impl CachingResolver { /// `hedge` while none has succeeded, and at once when one fails: a fast /// failure (`EAI_AGAIN` from an overloaded stub) must not fail every waiter /// while another attempt may still succeed. The last error is returned only -/// once every attempt has failed. -fn first_answer(lookup: &Lookup, host: &str, hedge: Duration) -> io::Result> { +/// once every attempt has failed, and `TimedOut` if none has answered by +/// `deadline`, so a resolver that hangs still settles the lookup. +fn first_answer( + lookup: &Lookup, + host: &str, + hedge: Duration, + deadline: Duration, +) -> io::Result> { + let started = Instant::now(); let (done_tx, done_rx) = std::sync::mpsc::channel(); let (mut attempts, mut running) = (0, 0); let mut last_error = None; @@ -210,7 +226,13 @@ fn first_answer(lookup: &Lookup, host: &str, hedge: Duration) -> io::Result return Ok(addrs), Ok(result) => { running -= 1; @@ -563,6 +585,21 @@ mod tests { release(&stall); } + #[tokio::test] + async fn a_lookup_whose_attempts_all_hang_times_out() { + let (lookup, calls, stall) = stalling(usize::MAX); + let mut r = CachingResolver::new(TTL, Duration::from_millis(10), lookup); + r.stuck_after = Duration::from_millis(100); + let r = Arc::new(r); + let err = tokio::time::timeout(Duration::from_secs(10), resolve(&r, "example.com")) + .await + .expect("the lookup never settled") + .unwrap_err(); + assert!(err.contains("timed out"), "{err}"); + assert_eq!(calls.load(Ordering::SeqCst), MAX_ATTEMPTS); + release(&stall); + } + #[tokio::test] async fn a_lookup_makes_at_most_max_attempts() { let (lookup, calls, stall) = stalling(usize::MAX); diff --git a/src/client/http.rs b/src/client/http.rs index f69acc25..8545e0bc 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1105,6 +1105,26 @@ mod tests { assert!(client.is_ok()); } + #[tokio::test] + async fn clients_resolve_hosts_through_the_shared_dns_cache() { + use wiremock::matchers::any; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(any()) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + let mut config = HttpClientConfig::default(); + config.tls.enabled = Some(false); + let client = DatabricksHttpClient::new(config, default_retry_configs()).unwrap(); + // A name, not the mock's IP literal, so a resolver is consulted. + let url = format!("http://localhost:{}/", server.address().port()); + client.inner().get(url).send().await.expect("request"); + // Only clients built here write to the shared cache. + assert!(crate::client::dns::CachingResolver::shared().has_answer("localhost")); + } + #[tokio::test] async fn test_auth_header_after_set() { let config = HttpClientConfig::default(); From d8d7e14f567ac2c18d79956266057d62e827f8f4 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 01:50:18 +0000 Subject: [PATCH 12/12] perf(client): start DNS lookup threads outside the cache lock entry() spawned the coordinator thread while holding the process-wide entries mutex, so every resolve for every host waited behind each spawn. The slot (and its channel) is now inserted under the lock and the thread is spawned after it is released. The immediate retry after any failure is documented as intended (getaddrinfo errors can't be told apart), and the negative-TTL test is split into two that don't depend on timing. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/dns.rs | 69 +++++++++++++++++++++++++++++++---------------- 1 file changed, 46 insertions(+), 23 deletions(-) diff --git a/src/client/dns.rs b/src/client/dns.rs index c64af238..5e73da86 100644 --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -112,7 +112,25 @@ impl CachingResolver { /// The lookup to join for `host`: one in flight, a recent answer, or a new /// lookup when the last one expired. fn entry(&self, host: &str) -> Entry { - let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + let (tx, rx) = { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + match self.current_or_insert(&mut entries, host) { + Ok(current) => return current, + Err(new) => new, + } + }; + // Spawned after the lock is released: every resolve takes that lock. + self.start_lookup(host, tx); + rx + } + + /// The usable entry for `host`, or the sender and receiver of a new one + /// just inserted for it. + fn current_or_insert( + &self, + entries: &mut HashMap, + host: &str, + ) -> Result>, Entry)> { let usable = |slot: &Slot| match &*slot.entry.borrow() { // An unanswered entry is joined only while something can still // answer it. @@ -126,7 +144,7 @@ impl CachingResolver { }; if let Some(current) = entries.get(host) { if usable(current) { - return current.entry.clone(); + return Ok(current.entry.clone()); } } if entries.len() >= MAX_HOSTS { @@ -135,14 +153,14 @@ impl CachingResolver { entries.clear(); } } - let entry = self.start_lookup(host); + let (tx, rx) = watch::channel(None); let slot = Slot { - entry: entry.clone(), + entry: rx.clone(), started: Instant::now(), pid: std::process::id(), }; entries.insert(host.to_owned(), slot); - entry + Err((tx, rx)) } /// Whether `host` has a cached successful answer (tests only). @@ -158,27 +176,23 @@ impl CachingResolver { /// answer itself: waiters from other sessions depend on it, so it must not /// be abandoned when the caller that started it is cancelled or its /// runtime shuts down. See [`first_answer`] for how attempts are made. - fn start_lookup(&self, host: &str) -> Entry { - let (tx, rx) = watch::channel(None); + fn start_lookup(&self, host: &str, tx: watch::Sender>) { let lookup = Arc::clone(&self.lookup); let (hedge, deadline) = (self.hedge, self.stuck_after); let host = host.to_owned(); + let tx = Arc::new(tx); + let thread_tx = Arc::clone(&tx); let spawned = std::thread::Builder::new() .name("dbx-sql-kernel-dns".to_owned()) .spawn(move || { let result = first_answer(&lookup, &host, hedge, deadline); - tx.send_replace(Some(( + thread_tx.send_replace(Some(( result.map(Arc::from).map_err(Arc::new), Instant::now(), ))); }); - match spawned { - Ok(_) => rx, - Err(e) => { - let (tx, rx) = watch::channel(None); - tx.send_replace(Some((Err(Arc::new(e)), Instant::now()))); - rx - } + if let Err(e) = spawned { + tx.send_replace(Some((Err(Arc::new(e)), Instant::now()))); } } } @@ -235,6 +249,11 @@ fn first_answer( match done_rx.recv_timeout(hedge.min(left)) { Ok(Ok(addrs)) if !addrs.is_empty() => return Ok(addrs), Ok(result) => { + // Retried at once whatever the error: std reports every + // getaddrinfo failure as the same kind with gai_strerror's + // localized text, so a final NXDOMAIN can't be told from a + // transient EAI_AGAIN. A host that doesn't resolve costs + // MAX_ATTEMPTS queries per NEGATIVE_TTL rather than one. running -= 1; last_error = Some(result.err().unwrap_or_else(|| { io::Error::new(io::ErrorKind::NotFound, "DNS lookup returned no addresses") @@ -357,10 +376,10 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn failures_reach_current_waiters_and_are_reused_briefly() { + async fn failures_reach_current_waiters_and_are_reused() { let (lookup, calls) = counting(Duration::from_millis(50), true); let mut r = CachingResolver::new(TTL, HEDGE, lookup); - r.negative_ttl = Duration::from_millis(200); + r.negative_ttl = Duration::from_secs(60); let r = Arc::new(r); let tasks: Vec<_> = (0..16) .map(|_| { @@ -382,13 +401,17 @@ mod tests { MAX_ATTEMPTS, "a recent failure is reused" ); - tokio::time::sleep(Duration::from_millis(300)).await; + } + + #[tokio::test] + async fn expired_failures_are_looked_up_again() { + let (lookup, calls) = counting(Duration::ZERO, true); + let mut r = CachingResolver::new(TTL, HEDGE, lookup); + r.negative_ttl = Duration::ZERO; + let r = Arc::new(r); assert!(resolve(&r, "example.com").await.is_err()); - assert_eq!( - calls.load(Ordering::SeqCst), - 2 * MAX_ATTEMPTS, - "an expired failure is looked up again" - ); + assert!(resolve(&r, "example.com").await.is_err()); + assert_eq!(calls.load(Ordering::SeqCst), 2 * MAX_ATTEMPTS); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)]