You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "milenkovicm (via GitHub)" <gi...@apache.org> on 2026/04/26 13:35:35 UTC

[PR] feat: Support cacheing remote shuffle reader clients in executor. [datafusion-ballista]

milenkovicm opened a new pull request, #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578

   # Which issue does this PR close?
   
   Closes #736.
   
   # Rationale for this change
   
   As mentioned in https://github.com/apache/datafusion-ballista/pull/1388#issuecomment-3980564362 we may get out of ports to establish connection in some cases. Also, sometimes connection establishment may be expensive. Hence we need to provide a way to cache established connections.
   
   # What changes are included in this PR?
   
   A new pluggable trait `BallistaClientPool` which can support different strategies of client caching 
   
   # Are there any user-facing changes?
   
   changes are backward compatible, as new functionality has to be enabled using `SET ballista.client.pool=true`
   
   also, this change supersedes #1388
   
   # TODO:
   
   - [ ] configurable pool timeout and purging tread interval
   - [ ] wire up with executor


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3163559637


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,351 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port, config)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+///
+/// The `DefaultBallistaClientPool` uses the (host, port, config) to identify a connection.
+/// Therefore changing connection config might leave pooled connections
+/// with older config unused until they expire.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer
+    /// than defined `idle_timeout`.
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?

Review Comment:
   maybe it would make sense to have warning for ttl < 15 but then there would be a bit of explaining needed.
   i was thinking to add it to cli help, but this is implementation specific as well. 
   I'd propose to keep it as it is and add it later if needed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3163072550


##########
ballista/core/src/client.rs:
##########
@@ -114,6 +114,24 @@ impl BallistaClient {
         })
     }
 
+    /// creates a ballista client to be used for testing
+    /// it connects lazily and which can not really
+    /// be reconfigured.
+    pub fn new_for_test(host: &str, port: u16) -> Self {

Review Comment:
   It should but apparently it does not work across different crates, or I'm doing something wrong 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache remote shuffle reader clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3152009573


##########
ballista/core/src/client_pool.rs:
##########
@@ -0,0 +1,426 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient`` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire` a
+//! `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! If the connection errored, call`PooledClient::discard` before dropping so
+//! the pool closes the channel rather than reusing it.
+//!
+//! A background tokio task evicts idle connections that have not been returned
+//! within the configured `idle_timeout`.
+
+use crate::client::BallistaClient;
+use crate::error::Result;
+use crate::extension::BallistaConfigGrpcEndpoint;
+use crate::utils::GrpcClientConfig;
+use async_trait::async_trait;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::ops::{Deref, DerefMut};
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// PooledClient guard
+// ---------------------------------------------------------------------------
+
+/// A [BallistaClient] checked out from a pool.
+///
+/// Implements [Deref] / [DerefMut] so it can be used exactly like a
+/// [BallistaClient]. On drop, the inner client is returned to the pool
+/// automatically. Call [PooledClient::discard] before dropping if the
+/// connection should **not** be reused (e.g. after a transport error).
+pub struct PooledClient {
+    client: BallistaClient,
+    /// Invoked in `Drop::drop` to push the client back into the idle deque.
+    /// `None` after `discard()` is called.
+    return_fn: Option<Box<dyn FnOnce(BallistaClient) + Send>>,
+}
+
+impl PooledClient {
+    pub(crate) fn new(
+        client: BallistaClient,
+        return_fn: Box<dyn FnOnce(BallistaClient) + Send>,
+    ) -> Self {
+        Self {
+            client,
+            return_fn: Some(return_fn),
+        }
+    }
+
+    /// Close the connection instead of returning it to the pool.
+    pub fn discard(mut self) {
+        self.return_fn = None;
+    }
+}
+
+impl Deref for PooledClient {
+    type Target = BallistaClient;
+    fn deref(&self) -> &Self::Target {
+        &self.client
+    }
+}
+
+impl DerefMut for PooledClient {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.client
+    }
+}
+
+impl Drop for PooledClient {
+    fn drop(&mut self) {
+        if let Some(f) = self.return_fn.take() {
+            let client = self.client.clone();
+            f(client);
+        }
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Trait
+// ---------------------------------------------------------------------------
+
+/// Manages a pool of reusable [BallistaClient] connections.
+#[async_trait]
+pub trait BallistaClientPool: Send + Sync + Debug {
+    /// Acquire an idle client for `(host, port)`, or create a new one if the
+    /// pool is empty for that key. The returned [PooledClient] returns itself
+    /// to the pool on drop.
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient>;
+
+    /// Remove all idle clients that have been sitting unused longer than the
+    /// configured idle timeout. Called automatically by the background task in
+    /// [DefaultBallistaClientPool]; can also be invoked on demand.
+    async fn evict_idle(&self);
+}
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since <= deadline) {
+            deque.pop_front();
+        }
+        !deque.is_empty()
+    });
+}
+
+#[async_trait]
+impl BallistaClientPool for DefaultBallistaClientPool {
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient> {
+        let key = (host.to_string(), port);
+
+        // Pop the most-recently-used idle client. The DashMap shard lock is
+        // held only for the duration of the pop — released before the async
+        // BallistaClient::try_new call below.
+        let maybe_idle = self
+            .inner
+            .idle
+            .get_mut(&key)
+            .and_then(|mut deque| deque.pop_back())
+            .map(|e| e.client);
+
+        let client = match maybe_idle {
+            Some(c) => {

Review Comment:
   yes, this is boundary case, we could probably use all configuration values as key, but at the moment it looks like an overkill. would suggest to keep it as it is and just document behaviour 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache remote shuffle reader clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3152049113


##########
ballista/core/Cargo.toml:
##########
@@ -49,6 +49,7 @@ async-trait = { workspace = true }
 aws-config = { version = "1.8.16", optional = true }
 aws-credential-types = { version = "1.2.0", optional = true }
 chrono = { version = "0.4", default-features = false }
+dashmap = { workspace = true }

Review Comment:
   DefaultBallistaPool can be moved to executor, where dashmap is already used



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache remote shuffle reader clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#issuecomment-4330823344

   ### Code review
   
   Found 8 issues:
   
   1. Breaking public API: `Executor::new` signature changed from `Option<Arc<dyn ExecutionEngine>>` to `Arc<dyn ExecutionEngine>`. The PR description says "backward compatible" but downstream callers passing `None` won't compile. Consider keeping the old form, adding a `#[deprecated]` shim, or applying the `api change` label.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/executor/src/executor.rs#L120-L150
   
   2. Breaking public API: `pub fn change_work_dir` on `pub struct ShuffleReaderExec` is renamed to `with_work_dir` with no deprecation alias. Custom `ExecutionEngine` impls in downstream crates that call the old name will break.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/core/src/execution_plans/shuffle_reader.rs#L510-L520
   
   3. Cached connections retain stale `GrpcClientConfig`. `ShuffleReaderExec::execute()` derives `GrpcClientConfig` per task from `TaskContext::session_config()` (so retry counts from #1577 can vary), but the pool keys only on `(host, port)` and returns idle clients with their original config. Either include the relevant config fields in the cache key, rebuild the client when config differs, or document the limitation.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/core/src/client_pool.rs#L290-L310
   
   4. Eviction boundary off-by-one: `while deque.front().is_some_and(|e| e.idle_since <= deadline)` evicts entries idle for *exactly* `idle_timeout`, but the rustdoc says "longer than" the timeout. Should be `<` for the documented semantics.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/core/src/client_pool.rs#L268-L275
   
   5. Module-level rustdoc inverts the eviction policy: "evicts idle connections that have not been returned within the configured `idle_timeout`". The eviction task only sees connections that *have* been returned; it removes ones that have sat idle for longer than `idle_timeout`.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/core/src/client_pool.rs#L20-L35
   
   6. Typo "Number of second" should be "Number of seconds" in both the rustdoc and the clap `help` string for `--connection-cache`. User-visible at the CLI; appears in two locations.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/executor/src/config.rs#L150-L160
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/executor/src/executor_process.rs#L138-L145
   
   7. Truncated rustdoc on `with_eviction_thread`: ``/// Create a pool that evicts connections idle longer than \`idle_timeout\`,`` — ends mid-sentence, looks copy-pasted from `new()`. `ballista-core` has `#![warn(missing_docs)]` so doc quality on public API matters.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/core/src/client_pool.rs#L150-L160
   
   8. `dashmap` is added as an unconditional dependency in `ballista-core`, even though pooling is runtime-opt-in (`--connection-cache` defaults to 0) and only `client_pool.rs` uses it. Consider gating both the dep and the module behind a cargo feature so `--no-default-features` builds stay lean.
   
   https://github.com/apache/datafusion-ballista/blob/011b0d3dadd2f74b5da5ecc2d33df04237a36b07/ballista/core/Cargo.toml#L18-L25


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3178442036


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,352 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps `BallistaClients` as `VecDeque<IdleEntry>` per `(host, port, config)`.
+/// Idle clients are evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+///
+/// The `DefaultBallistaClientPool` uses the (host, port, config) to identify a connection.
+/// Therefore changing connection config might leave pooled connections
+/// with older config unused until they expire.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer
+    /// than defined `idle_timeout`.
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // there is no empirical evidence why 15 is selected.
+        // we can revisit if interval < 15 is needed
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    #[cfg(test)]
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    // This way pool can shrink in case of low utilization.
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since < deadline) {
+            // evict from front of the queue
+            deque.pop_front();
+        }
+        !deque.is_empty()
+    });
+}
+
+#[async_trait]
+impl BallistaClientPool for DefaultBallistaClientPool {
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient> {
+        let key = (host.to_string(), port, config.clone());

Review Comment:
   Customise endpoint is compile time, it should not change. I propose it ignore it for now 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "martin-g (via GitHub)" <gi...@apache.org>.
martin-g commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3161295444


##########
ballista/core/src/execution_plans/shuffle_reader.rs:
##########
@@ -94,19 +96,49 @@ impl ShuffleReaderExec {
             partition,
             metrics: ExecutionPlanMetricsSet::new(),
             properties,
-            work_dir: None, // to be updated at the executor side
+            work_dir: None,    // to be updated at the executor side
+            client_pool: None, // to be updated at the executor side
         })
     }
 
     /// changes work dir where shuffle files are located
-    pub fn change_work_dir(&self, work_dir: String) -> Self {
+    pub fn with_work_dir(&self, work_dir: String) -> Self {
         Self {
             stage_id: self.stage_id,
             schema: self.schema.clone(),
             partition: self.partition.clone(),
             metrics: self.metrics.clone(),
             properties: self.properties.clone(),
             work_dir: Some(work_dir),
+            client_pool: self.client_pool.clone(),
+        }
+    }
+    /// creates new shuffle reader with client pool
+    pub fn with_client_pool(&self, client_pool: Arc<dyn BallistaClientPool>) -> Self {
+        Self {
+            stage_id: self.stage_id,
+            schema: self.schema.clone(),
+            partition: self.partition.clone(),
+            metrics: self.metrics.clone(),
+            properties: self.properties.clone(),
+            work_dir: self.work_dir.clone(),
+            client_pool: Some(client_pool),
+        }
+    }
+    /// creates new shuffle reader with client pool and work dir
+    pub fn with_client_pool_and_work_dir(

Review Comment:
   Is this method really needed ?
   The user could do it in two steps: `with_client_pool(client_pool).with_work_dir(work_dir)`
   At the moment `fn with_client_pool()` is not used anywhere.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3163085758


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,351 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port, config)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+///
+/// The `DefaultBallistaClientPool` uses the (host, port, config) to identify a connection.
+/// Therefore changing connection config might leave pooled connections
+/// with older config unused until they expire.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer
+    /// than defined `idle_timeout`.
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    #[cfg(test)]
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    // This way pool can shrink in case of low utilization.
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since < deadline) {
+            // evict from front of the queue
+            deque.pop_front();
+        }
+        !deque.is_empty()
+    });
+}
+
+#[async_trait]
+impl BallistaClientPool for DefaultBallistaClientPool {
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient> {
+        let key = (host.to_string(), port, config.clone());
+
+        // Pop the most-recently-used idle client. The DashMap shard lock is
+        // held only for the duration of the pop — released before the async
+        // BallistaClient::try_new call below.
+        let maybe_idle_client = self
+            .inner
+            .idle
+            .get_mut(&key)
+            .and_then(|mut deque| deque.pop_back()) // acquire from back of the queue
+            .map(|e| e.client);
+
+        let client = match maybe_idle_client {
+            Some(client) => {
+                log::trace!(
+                    "client connection pool - returning cached connection - host:{host}, port:{port}"
+                );
+                client

Review Comment:
   My understanding tonic should handle reconnection automatically 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3178424665


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,352 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps `BallistaClients` as `VecDeque<IdleEntry>` per `(host, port, config)`.
+/// Idle clients are evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+///
+/// The `DefaultBallistaClientPool` uses the (host, port, config) to identify a connection.
+/// Therefore changing connection config might leave pooled connections
+/// with older config unused until they expire.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer
+    /// than defined `idle_timeout`.
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // there is no empirical evidence why 15 is selected.
+        // we can revisit if interval < 15 is needed
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    #[cfg(test)]
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    // This way pool can shrink in case of low utilization.
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since < deadline) {
+            // evict from front of the queue
+            deque.pop_front();
+        }
+        !deque.is_empty()
+    });
+}
+
+#[async_trait]
+impl BallistaClientPool for DefaultBallistaClientPool {
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient> {
+        let key = (host.to_string(), port, config.clone());

Review Comment:
   key is missing `customize_endpoint`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3172572850


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,352 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;

Review Comment:
   i agree, we can do that as a follow up 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "danielhumanmod (via GitHub)" <gi...@apache.org>.
danielhumanmod commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3172123992


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,352 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;

Review Comment:
   Based on my understanding, the current pool is TTL-based and only evicts clients once they have been idle longer than the configured TTL.
   
   One of my two-cent thought: should we also consider a per-endpoint or global max idle limit, and evict/drop clients when that limit is reached? That would help prevent the pool from retaining too many idle clients after a burst of high-concurrency shuffle fetches.
   
   Not a blocker tho, we can also consider adding that if we meet this kind of issue
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3178425178


##########
ballista/executor/src/execution_engine.rs:
##########
@@ -98,8 +115,18 @@ impl ExecutionEngine for DefaultExecutionEngine {
         let plan = plan
             .transform(|p| {
                 if let Some(reader) = p.as_any().downcast_ref::<ShuffleReaderExec>() {
-                    let reader = Arc::new(reader.change_work_dir(work_dir.to_string()));
-                    Ok(Transformed::yes(reader))
+                    // if client_pool is not None we need to get clone of it and
+                    // invoke reader.with_client_pool_and_work_dir

Review Comment:
   I do not see method `with_client_pool_and_work_dir` being called



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#issuecomment-4347167943

   Thanks @milenkovicm. I will try and start reviewing this one tonight.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3178423484


##########
ballista/core/src/client_pool.rs:
##########
@@ -0,0 +1,107 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+
+use crate::client::BallistaClient;
+use crate::error::Result;
+use crate::extension::BallistaConfigGrpcEndpoint;
+use crate::utils::GrpcClientConfig;
+use async_trait::async_trait;
+use std::fmt::Debug;
+use std::ops::{Deref, DerefMut};
+use std::sync::Arc;
+
+// ---------------------------------------------------------------------------
+// Trait
+// ---------------------------------------------------------------------------
+
+/// Manages a pool of reusable [BallistaClient] connections.
+#[async_trait]
+pub trait BallistaClientPool: Send + Sync + Debug {
+    /// Acquire an idle client for `(host, port)`, or create a new one if the

Review Comment:
   doc comment says key is `(host, port)` but should be `(host, port, config, customize_endpoint)` ?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "martin-g (via GitHub)" <gi...@apache.org>.
martin-g commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3161253476


##########
ballista/core/src/client.rs:
##########
@@ -114,6 +114,24 @@ impl BallistaClient {
         })
     }
 
+    /// creates a ballista client to be used for testing
+    /// it connects lazily and which can not really
+    /// be reconfigured.
+    pub fn new_for_test(host: &str, port: u16) -> Self {

Review Comment:
   There is no `#[cfg(test)]`.
   Does it need to be here ? It could be a helper method in `mod tests` too



##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,351 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per

Review Comment:
   ```suggestion
   //! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
   ```



##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,351 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port, config)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+///
+/// The `DefaultBallistaClientPool` uses the (host, port, config) to identify a connection.
+/// Therefore changing connection config might leave pooled connections
+/// with older config unused until they expire.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer
+    /// than defined `idle_timeout`.
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    #[cfg(test)]
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    // This way pool can shrink in case of low utilization.
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since < deadline) {
+            // evict from front of the queue
+            deque.pop_front();
+        }
+        !deque.is_empty()
+    });
+}
+
+#[async_trait]
+impl BallistaClientPool for DefaultBallistaClientPool {
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient> {
+        let key = (host.to_string(), port, config.clone());
+
+        // Pop the most-recently-used idle client. The DashMap shard lock is
+        // held only for the duration of the pop — released before the async
+        // BallistaClient::try_new call below.
+        let maybe_idle_client = self
+            .inner
+            .idle
+            .get_mut(&key)
+            .and_then(|mut deque| deque.pop_back()) // acquire from back of the queue
+            .map(|e| e.client);
+
+        let client = match maybe_idle_client {
+            Some(client) => {
+                log::trace!(
+                    "client connection pool - returning cached connection - host:{host}, port:{port}"
+                );
+                client

Review Comment:
   does it need to check whether it is still connected ?
   if the remote party has been restarted in the meantime then the client will probably fail without reconnecting.



##########
ballista/core/src/execution_plans/shuffle_reader.rs:
##########
@@ -94,19 +96,49 @@ impl ShuffleReaderExec {
             partition,
             metrics: ExecutionPlanMetricsSet::new(),
             properties,
-            work_dir: None, // to be updated at the executor side
+            work_dir: None,    // to be updated at the executor side
+            client_pool: None, // to be updated at the executor side
         })
     }
 
     /// changes work dir where shuffle files are located
-    pub fn change_work_dir(&self, work_dir: String) -> Self {
+    pub fn with_work_dir(&self, work_dir: String) -> Self {
         Self {
             stage_id: self.stage_id,
             schema: self.schema.clone(),
             partition: self.partition.clone(),
             metrics: self.metrics.clone(),
             properties: self.properties.clone(),
             work_dir: Some(work_dir),
+            client_pool: self.client_pool.clone(),
+        }
+    }
+    /// creates new shuffle reader with client pool
+    pub fn with_client_pool(&self, client_pool: Arc<dyn BallistaClientPool>) -> Self {
+        Self {
+            stage_id: self.stage_id,
+            schema: self.schema.clone(),
+            partition: self.partition.clone(),
+            metrics: self.metrics.clone(),
+            properties: self.properties.clone(),
+            work_dir: self.work_dir.clone(),
+            client_pool: Some(client_pool),
+        }
+    }
+    /// creates new shuffle reader with client pool and work dir
+    pub fn with_client_pool_and_work_dir(

Review Comment:
   Is this method really needed ?
   The user could could it in two steps: `with_client_pool(client_pool).with_work_dir(work_dir)`
   At the moment `fn with_client_pool()` is not used anywhere.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3163072550


##########
ballista/core/src/client.rs:
##########
@@ -114,6 +114,24 @@ impl BallistaClient {
         })
     }
 
+    /// creates a ballista client to be used for testing
+    /// it connects lazily and which can not really
+    /// be reconfigured.
+    pub fn new_for_test(host: &str, port: u16) -> Self {

Review Comment:
   It shot but apparently it does not work across different crates, or I'm doing something wrong 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache remote shuffle reader clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3150510976


##########
ballista/core/src/execution_plans/shuffle_reader.rs:
##########
@@ -95,18 +97,48 @@ impl ShuffleReaderExec {
             metrics: ExecutionPlanMetricsSet::new(),
             properties,
             work_dir: None, // to be updated at the executor side
+            client_pool: None,
         })
     }
 
     /// changes work dir where shuffle files are located
-    pub fn change_work_dir(&self, work_dir: String) -> Self {
+    pub fn with_work_dir(&self, work_dir: String) -> Self {

Review Comment:
   Small thought on the rename from `change_work_dir`. Since this is `pub` on a public struct, custom `ExecutionEngine` impls in downstream projects may be calling it. Would it be worth keeping a `#[deprecated]` shim under the old name that forwards to `with_work_dir`? That way folks get a warning instead of a hard compile error.



##########
ballista/executor/src/executor.rs:
##########
@@ -127,7 +127,30 @@ impl Executor {
         function_registry: Arc<BallistaFunctionRegistry>,
         metrics_collector: Arc<dyn ExecutorMetricsCollector>,
         concurrent_tasks: usize,
-        execution_engine: Option<Arc<dyn ExecutionEngine>>,
+        execution_engine: Arc<dyn ExecutionEngine>,

Review Comment:
   Nice work splitting out `with_default_execution_engine`. One thing worth checking. This changes `Executor::new` from `Option<Arc<dyn ExecutionEngine>>` to `Arc<dyn ExecutionEngine>`. Anyone downstream calling `Executor::new(..., None)` will hit a compile error once this lands. Could we keep the old signature and have `with_default_execution_engine` be purely additive? If we do want the breaking change, it might be worth flagging the PR with the `api change` label.



##########
ballista/core/src/client_pool.rs:
##########
@@ -0,0 +1,426 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient`` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire` a
+//! `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! If the connection errored, call`PooledClient::discard` before dropping so
+//! the pool closes the channel rather than reusing it.
+//!
+//! A background tokio task evicts idle connections that have not been returned
+//! within the configured `idle_timeout`.
+
+use crate::client::BallistaClient;
+use crate::error::Result;
+use crate::extension::BallistaConfigGrpcEndpoint;
+use crate::utils::GrpcClientConfig;
+use async_trait::async_trait;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::ops::{Deref, DerefMut};
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// PooledClient guard
+// ---------------------------------------------------------------------------
+
+/// A [BallistaClient] checked out from a pool.
+///
+/// Implements [Deref] / [DerefMut] so it can be used exactly like a
+/// [BallistaClient]. On drop, the inner client is returned to the pool
+/// automatically. Call [PooledClient::discard] before dropping if the
+/// connection should **not** be reused (e.g. after a transport error).
+pub struct PooledClient {
+    client: BallistaClient,
+    /// Invoked in `Drop::drop` to push the client back into the idle deque.
+    /// `None` after `discard()` is called.
+    return_fn: Option<Box<dyn FnOnce(BallistaClient) + Send>>,
+}
+
+impl PooledClient {
+    pub(crate) fn new(
+        client: BallistaClient,
+        return_fn: Box<dyn FnOnce(BallistaClient) + Send>,
+    ) -> Self {
+        Self {
+            client,
+            return_fn: Some(return_fn),
+        }
+    }
+
+    /// Close the connection instead of returning it to the pool.
+    pub fn discard(mut self) {
+        self.return_fn = None;
+    }
+}
+
+impl Deref for PooledClient {
+    type Target = BallistaClient;
+    fn deref(&self) -> &Self::Target {
+        &self.client
+    }
+}
+
+impl DerefMut for PooledClient {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.client
+    }
+}
+
+impl Drop for PooledClient {
+    fn drop(&mut self) {
+        if let Some(f) = self.return_fn.take() {
+            let client = self.client.clone();
+            f(client);
+        }
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Trait
+// ---------------------------------------------------------------------------
+
+/// Manages a pool of reusable [BallistaClient] connections.
+#[async_trait]
+pub trait BallistaClientPool: Send + Sync + Debug {
+    /// Acquire an idle client for `(host, port)`, or create a new one if the
+    /// pool is empty for that key. The returned [PooledClient] returns itself
+    /// to the pool on drop.
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient>;
+
+    /// Remove all idle clients that have been sitting unused longer than the
+    /// configured idle timeout. Called automatically by the background task in
+    /// [DefaultBallistaClientPool]; can also be invoked on demand.
+    async fn evict_idle(&self);
+}
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {

Review Comment:
   Looks like this doc got truncated. It ends on a comma with no predicate. Looks like maybe an in-progress copy from `new()` below? Could be filled in with something like 'using a background eviction thread' to round out the sentence.



##########
ballista/core/src/client_pool.rs:
##########
@@ -0,0 +1,426 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient`` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire` a
+//! `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! If the connection errored, call`PooledClient::discard` before dropping so
+//! the pool closes the channel rather than reusing it.
+//!
+//! A background tokio task evicts idle connections that have not been returned
+//! within the configured `idle_timeout`.
+
+use crate::client::BallistaClient;
+use crate::error::Result;
+use crate::extension::BallistaConfigGrpcEndpoint;
+use crate::utils::GrpcClientConfig;
+use async_trait::async_trait;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::ops::{Deref, DerefMut};
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// PooledClient guard
+// ---------------------------------------------------------------------------
+
+/// A [BallistaClient] checked out from a pool.
+///
+/// Implements [Deref] / [DerefMut] so it can be used exactly like a
+/// [BallistaClient]. On drop, the inner client is returned to the pool
+/// automatically. Call [PooledClient::discard] before dropping if the
+/// connection should **not** be reused (e.g. after a transport error).
+pub struct PooledClient {
+    client: BallistaClient,
+    /// Invoked in `Drop::drop` to push the client back into the idle deque.
+    /// `None` after `discard()` is called.
+    return_fn: Option<Box<dyn FnOnce(BallistaClient) + Send>>,
+}
+
+impl PooledClient {
+    pub(crate) fn new(
+        client: BallistaClient,
+        return_fn: Box<dyn FnOnce(BallistaClient) + Send>,
+    ) -> Self {
+        Self {
+            client,
+            return_fn: Some(return_fn),
+        }
+    }
+
+    /// Close the connection instead of returning it to the pool.
+    pub fn discard(mut self) {
+        self.return_fn = None;
+    }
+}
+
+impl Deref for PooledClient {
+    type Target = BallistaClient;
+    fn deref(&self) -> &Self::Target {
+        &self.client
+    }
+}
+
+impl DerefMut for PooledClient {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.client
+    }
+}
+
+impl Drop for PooledClient {
+    fn drop(&mut self) {
+        if let Some(f) = self.return_fn.take() {
+            let client = self.client.clone();
+            f(client);
+        }
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Trait
+// ---------------------------------------------------------------------------
+
+/// Manages a pool of reusable [BallistaClient] connections.
+#[async_trait]
+pub trait BallistaClientPool: Send + Sync + Debug {
+    /// Acquire an idle client for `(host, port)`, or create a new one if the
+    /// pool is empty for that key. The returned [PooledClient] returns itself
+    /// to the pool on drop.
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient>;
+
+    /// Remove all idle clients that have been sitting unused longer than the
+    /// configured idle timeout. Called automatically by the background task in
+    /// [DefaultBallistaClientPool]; can also be invoked on demand.
+    async fn evict_idle(&self);
+}
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since <= deadline) {

Review Comment:
   Tiny boundary thing. The trait doc above (`evict_idle`) says 'sitting unused longer than the configured idle timeout', but `idle_since <= deadline` will also evict entries that are exactly at the timeout. Should this be a strict `<` to match the wording?



##########
ballista/core/Cargo.toml:
##########
@@ -49,6 +49,7 @@ async-trait = { workspace = true }
 aws-config = { version = "1.8.16", optional = true }
 aws-credential-types = { version = "1.2.0", optional = true }
 chrono = { version = "0.4", default-features = false }
+dashmap = { workspace = true }

Review Comment:
   Since pooling is opt-in at runtime (off by default via `--connection-cache 0`), would it make sense to gate `dashmap` and the new `client_pool` module behind a cargo feature? That way `--no-default-features` builds stay lean and folks who never enable pooling do not pull in dashmap.



##########
ballista/core/src/client_pool.rs:
##########
@@ -0,0 +1,426 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient`` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire` a
+//! `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! If the connection errored, call`PooledClient::discard` before dropping so
+//! the pool closes the channel rather than reusing it.
+//!
+//! A background tokio task evicts idle connections that have not been returned
+//! within the configured `idle_timeout`.
+
+use crate::client::BallistaClient;
+use crate::error::Result;
+use crate::extension::BallistaConfigGrpcEndpoint;
+use crate::utils::GrpcClientConfig;
+use async_trait::async_trait;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::ops::{Deref, DerefMut};
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// PooledClient guard
+// ---------------------------------------------------------------------------
+
+/// A [BallistaClient] checked out from a pool.
+///
+/// Implements [Deref] / [DerefMut] so it can be used exactly like a
+/// [BallistaClient]. On drop, the inner client is returned to the pool
+/// automatically. Call [PooledClient::discard] before dropping if the
+/// connection should **not** be reused (e.g. after a transport error).
+pub struct PooledClient {
+    client: BallistaClient,
+    /// Invoked in `Drop::drop` to push the client back into the idle deque.
+    /// `None` after `discard()` is called.
+    return_fn: Option<Box<dyn FnOnce(BallistaClient) + Send>>,
+}
+
+impl PooledClient {
+    pub(crate) fn new(
+        client: BallistaClient,
+        return_fn: Box<dyn FnOnce(BallistaClient) + Send>,
+    ) -> Self {
+        Self {
+            client,
+            return_fn: Some(return_fn),
+        }
+    }
+
+    /// Close the connection instead of returning it to the pool.
+    pub fn discard(mut self) {
+        self.return_fn = None;
+    }
+}
+
+impl Deref for PooledClient {
+    type Target = BallistaClient;
+    fn deref(&self) -> &Self::Target {
+        &self.client
+    }
+}
+
+impl DerefMut for PooledClient {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.client
+    }
+}
+
+impl Drop for PooledClient {
+    fn drop(&mut self) {
+        if let Some(f) = self.return_fn.take() {
+            let client = self.client.clone();
+            f(client);
+        }
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Trait
+// ---------------------------------------------------------------------------
+
+/// Manages a pool of reusable [BallistaClient] connections.
+#[async_trait]
+pub trait BallistaClientPool: Send + Sync + Debug {
+    /// Acquire an idle client for `(host, port)`, or create a new one if the
+    /// pool is empty for that key. The returned [PooledClient] returns itself
+    /// to the pool on drop.
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient>;
+
+    /// Remove all idle clients that have been sitting unused longer than the
+    /// configured idle timeout. Called automatically by the background task in
+    /// [DefaultBallistaClientPool]; can also be invoked on demand.
+    async fn evict_idle(&self);
+}
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?
+        let check_interval = Duration::from_secs((idle_timeout.as_secs() / 3).max(15));
+
+        if enable_eviction_thread {
+            tokio::spawn(async move {
+                log::debug!(
+                    "client connection pool - eviction thread started ... interval: {check_interval:?}"
+                );
+                let mut ticker = tokio::time::interval(check_interval);
+                loop {
+                    ticker.tick().await;
+
+                    match weak.upgrade() {
+                        None => break,
+                        Some(pool) => {
+                            log::trace!("client connection pool - evicting connections");
+                            evict(&pool.idle, pool.idle_timeout)
+                        }
+                    }
+                }
+                log::debug!("client connection pool - eviction thread ... DONE");
+            });
+        }
+
+        Self { inner }
+    }
+
+    /// Total number of idle connections currently held across all endpoints.
+    pub fn idle_count(&self) -> usize {
+        self.inner.idle.iter().map(|e| e.value().len()).sum()
+    }
+}
+
+fn evict(idle: &IdleMap, timeout: Duration) {
+    let deadline = Instant::now()
+        .checked_sub(timeout)
+        .unwrap_or_else(Instant::now);
+
+    // Drain expired entries from the front of each deque (oldest = front).
+    idle.retain(|_, deque| {
+        while deque.front().is_some_and(|e| e.idle_since <= deadline) {
+            deque.pop_front();
+        }
+        !deque.is_empty()
+    });
+}
+
+#[async_trait]
+impl BallistaClientPool for DefaultBallistaClientPool {
+    async fn acquire(
+        &self,
+        host: &str,
+        port: u16,
+        config: &GrpcClientConfig,
+        customize_endpoint: Option<Arc<BallistaConfigGrpcEndpoint>>,
+    ) -> Result<PooledClient> {
+        let key = (host.to_string(), port);
+
+        // Pop the most-recently-used idle client. The DashMap shard lock is
+        // held only for the duration of the pop — released before the async
+        // BallistaClient::try_new call below.
+        let maybe_idle = self
+            .inner
+            .idle
+            .get_mut(&key)
+            .and_then(|mut deque| deque.pop_back())
+            .map(|e| e.client);
+
+        let client = match maybe_idle {
+            Some(c) => {

Review Comment:
   Question about cached entries. The pool keys on `(host, port)`, but `GrpcClientConfig` carries values like `io_retries_times` and `io_retry_wait_time_ms` that became per-session-config in #1577. If those settings change between task runs, a recycled idle client will still be using whatever was in effect when it was first created. Is that something we should worry about in practice, or do those values rarely vary at runtime?



##########
ballista/core/src/client_pool.rs:
##########
@@ -0,0 +1,426 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient`` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire` a
+//! `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! If the connection errored, call`PooledClient::discard` before dropping so
+//! the pool closes the channel rather than reusing it.
+//!
+//! A background tokio task evicts idle connections that have not been returned

Review Comment:
   I think this sentence may be inverted. The eviction task only sees connections that have already been returned to the idle deque. So it removes ones that have been sitting idle (returned but not re-acquired) for longer than `idle_timeout`. Maybe reword to something like 'evicts connections that have sat idle longer than `idle_timeout`'?



##########
ballista/executor/src/config.rs:
##########
@@ -151,6 +151,13 @@ pub struct Config {
         help = "Metric collection policy of this executor instance"
     )]
     pub metric_collection_policy: ExecutorMetricCollectionPolicy,
+    /// Number of second established client connection should be cached (0 means no cache)
+    #[arg(
+        long,
+        default_value_t = 0,
+        help = "Number of second established client connection should be cached (0 means no cache) "

Review Comment:
   Tiny typo: `Number of second` should be `Number of seconds`. The same wording also appears in the rustdoc just above on line 154, and in `ballista/executor/src/executor_process.rs` around line 141. Worth fixing all three since the help string shows up in `--help` output.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "sandugood (via GitHub)" <gi...@apache.org>.
sandugood commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3160775784


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,351 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port, config)`. Idle clients are

Review Comment:
   ```suggestion
   /// Keeps a `VecDeque<IdleEntry>` per `(host, port, config)`, which is itself a specification of a BallistaClient and duration of its idle status.
   ```



##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,351 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque`` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;
+
+struct Inner {
+    idle: IdleMap,
+    idle_timeout: Duration,
+}
+
+/// Default pool implementation.
+///
+/// Keeps a `VecDeque<BallistaClient>` per `(host, port, config)`. Idle clients are
+/// evicted by a background tokio task that runs at `idle_timeout / 3`
+/// intervals (minimum 15 s). The task exits automatically when the pool `Arc`
+/// is dropped.
+///
+/// The `DefaultBallistaClientPool` uses the (host, port, config) to identify a connection.
+/// Therefore changing connection config might leave pooled connections
+/// with older config unused until they expire.
+
+#[derive(Clone)]
+pub struct DefaultBallistaClientPool {
+    inner: Arc<Inner>,
+}
+
+impl Debug for DefaultBallistaClientPool {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("DefaultBallistaClientPool").finish()
+    }
+}
+
+impl DefaultBallistaClientPool {
+    /// Create a pool that evicts connections idle longer
+    /// than defined `idle_timeout`.
+    pub fn with_eviction_thread(idle_timeout: Duration) -> Self {
+        Self::new(idle_timeout, true)
+    }
+
+    /// Create a pool that evicts connections idle longer than `idle_timeout`,
+    /// if `enable_eviction_thread` is enabled
+    pub fn new(idle_timeout: Duration, enable_eviction_thread: bool) -> Self {
+        let inner = Arc::new(Inner {
+            idle: DashMap::new(),
+            idle_timeout,
+        });
+
+        let weak: Weak<Inner> = Arc::downgrade(&inner);
+        // TODO: do we limit minimum interval here?

Review Comment:
   Since we add this in the user-facing config:
   If the user sets the `client_ttl` in the (1, 45) range it will be transformed into 15. Maybe add a warning when user sets this value in the config and it is in the (1, 45) range?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "danielhumanmod (via GitHub)" <gi...@apache.org>.
danielhumanmod commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3174953605


##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,352 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;

Review Comment:
   Thanks for the information, very helpful, didn't catch this at the first place🙏



##########
ballista/executor/src/client_pool.rs:
##########
@@ -0,0 +1,352 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Connection pool for `BallistaClient` instances.
+//!
+//! `DefaultBallistaClientPool` maintains a `VecDeque` of idle clients per
+//! `(host, port, config)` key backed by a `DashMap`. Callers `BallistaClientPool::acquire`
+//! a `PooledClient` guard; when the guard is dropped the underlying client is
+//! returned to the idle deque automatically.
+//!
+//! Connections could be discarded calling `PooledClient::discard` which will result
+//! of dropping connection rather than returning it to the pool. This could be
+//! used for error handling.
+//!
+//! A optional background tokio task evicts idle connections that have not been used
+//! within the configured `idle_timeout`.
+
+use async_trait::async_trait;
+use ballista_core::client::BallistaClient;
+use ballista_core::client_pool::{BallistaClientPool, PooledClient};
+use ballista_core::error::Result;
+use ballista_core::extension::BallistaConfigGrpcEndpoint;
+use ballista_core::utils::GrpcClientConfig;
+use dashmap::DashMap;
+use std::collections::VecDeque;
+use std::fmt::Debug;
+use std::sync::{Arc, Weak};
+use std::time::{Duration, Instant};
+
+// ---------------------------------------------------------------------------
+// DefaultBallistaClientPool
+// ---------------------------------------------------------------------------
+
+struct IdleEntry {
+    client: BallistaClient,
+    idle_since: Instant,
+}
+
+type IdleMap = DashMap<(String, u16, GrpcClientConfig), VecDeque<IdleEntry>>;

Review Comment:
   Thanks for the information, very helpful, didn't catch this at the first place🙏



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm merged PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache remote shuffle reader clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3151968906


##########
ballista/core/src/execution_plans/shuffle_reader.rs:
##########
@@ -95,18 +97,48 @@ impl ShuffleReaderExec {
             metrics: ExecutionPlanMetricsSet::new(),
             properties,
             work_dir: None, // to be updated at the executor side
+            client_pool: None,
         })
     }
 
     /// changes work dir where shuffle files are located
-    pub fn change_work_dir(&self, work_dir: String) -> Self {
+    pub fn with_work_dir(&self, work_dir: String) -> Self {

Review Comment:
   this method has been introduced in #1527 which has not been released yet, so nobody should be impacted 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3160059645


##########
ballista/executor/src/executor.rs:
##########
@@ -127,7 +127,30 @@ impl Executor {
         function_registry: Arc<BallistaFunctionRegistry>,
         metrics_collector: Arc<dyn ExecutorMetricsCollector>,
         concurrent_tasks: usize,
-        execution_engine: Option<Arc<dyn ExecutionEngine>>,
+        execution_engine: Arc<dyn ExecutionEngine>,

Review Comment:
   its a minimal change, not many users use this api, I suggest to keep the change as it is, if you agree 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3163093564


##########
ballista/core/src/execution_plans/shuffle_reader.rs:
##########
@@ -94,19 +96,49 @@ impl ShuffleReaderExec {
             partition,
             metrics: ExecutionPlanMetricsSet::new(),
             properties,
-            work_dir: None, // to be updated at the executor side
+            work_dir: None,    // to be updated at the executor side
+            client_pool: None, // to be updated at the executor side
         })
     }
 
     /// changes work dir where shuffle files are located
-    pub fn change_work_dir(&self, work_dir: String) -> Self {
+    pub fn with_work_dir(&self, work_dir: String) -> Self {
         Self {
             stage_id: self.stage_id,
             schema: self.schema.clone(),
             partition: self.partition.clone(),
             metrics: self.metrics.clone(),
             properties: self.properties.clone(),
             work_dir: Some(work_dir),
+            client_pool: self.client_pool.clone(),
+        }
+    }
+    /// creates new shuffle reader with client pool
+    pub fn with_client_pool(&self, client_pool: Arc<dyn BallistaClientPool>) -> Self {
+        Self {
+            stage_id: self.stage_id,
+            schema: self.schema.clone(),
+            partition: self.partition.clone(),
+            metrics: self.metrics.clone(),
+            properties: self.properties.clone(),
+            work_dir: self.work_dir.clone(),
+            client_pool: Some(client_pool),
+        }
+    }
+    /// creates new shuffle reader with client pool and work dir
+    pub fn with_client_pool_and_work_dir(

Review Comment:
   You're right, I was trying to save few clones



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#discussion_r3178425605


##########
ballista/core/src/lib.rs:
##########
@@ -33,6 +33,8 @@ pub fn print_version() {
 
 /// Client utilities for connecting to Ballista schedulers.
 pub mod client;
+/// Connection pool for reusing `BallistaClient`` instances across requests.

Review Comment:
   ```suggestion
   /// Connection pool for reusing `BallistaClient` instances across requests.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Cache ballista clients on executor [datafusion-ballista]

Posted by "milenkovicm (via GitHub)" <gi...@apache.org>.
milenkovicm commented on PR #1578:
URL: https://github.com/apache/datafusion-ballista/pull/1578#issuecomment-4342640812

   @martin-g @danielhumanmod @sandugood  it would be great if you could review this change. thanks a lot 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org