From e8920d8d482855c2513c61286aea740139769a92 Mon Sep 17 00:00:00 2001 From: cathleeny <58714163+cathleeny@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:21:26 +0000 Subject: [PATCH] fix(session): free the transport when a session closes `ResultReaderFactory` held a strong `Arc` back to the `SeaRestTransport` that owns it, so the two formed a reference cycle and the transport was never dropped. Every closed session leaked its transport, HTTP client and tokio runtime handle. The Python binding runs one tokio runtime per session, and a live handle keeps that runtime's IO driver open after shutdown: two epoll fds, one eventfd and one signal socket per closed session, until the process hits `Too many open files`. The factory now holds a `Weak` reference and upgrades it when it builds a CloudFetch or inline-streaming reader. Readers keep a strong reference, so an open result stream still works after `Session::close`. Signed-off-by: cathleeny <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 1 + src/client/sea.rs | 6 +++--- src/reader/mod.rs | 49 ++++++++++++++++++++++++++++--------------- src/session.rs | 53 +++++++++++++++++++++++++++++++++++++++++------ 4 files changed, 83 insertions(+), 26 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..0c7a0055 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,6 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. +- Closing a `Session` now frees its transport, HTTP client and tokio runtime handle. A reference cycle between the transport and its result-reader factory kept them alive, so bindings that run one tokio runtime per session (Python) leaked four file descriptors per closed session until the process hit `Too many open files`. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/client/sea.rs b/src/client/sea.rs index 2a490aac..b680ef07 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -171,7 +171,7 @@ fn timeout_query_id(params: &ExecuteParams) -> Option { /// /// This client implements the `Transport` trait using REST endpoints. /// The `reader_factory` is set after construction via `set_reader_factory()` because -/// `ResultReaderFactory` needs `Arc` which requires wrapping +/// `ResultReaderFactory` needs a `Weak`, which requires wrapping /// `SeaRestTransport` in `Arc` first. pub(crate) struct SeaRestTransport { http_client: Arc, @@ -208,7 +208,7 @@ impl SeaRestTransport { /// /// After construction, call `set_reader_factory()` to enable result reader creation. /// This two-step initialization is required because `ResultReaderFactory` needs - /// `Arc`, which is only available after wrapping in `Arc`. + /// `Weak`, which is only available after wrapping in `Arc`. pub fn new( http_client: Arc, host: impl Into, @@ -1938,7 +1938,7 @@ mod tests { )); let runtime_handle = tokio::runtime::Handle::current(); let reader_factory = ResultReaderFactory::new( - transport.clone() as Arc, + Arc::::downgrade(&transport), http_client, CloudFetchConfig::default(), PostProcessOptions::default(), diff --git a/src/reader/mod.rs b/src/reader/mod.rs index c9532fbf..2ce9c00d 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -42,7 +42,7 @@ use arrow_ipc::reader::StreamReader; use arrow_schema::{ArrowError, Field, Schema, SchemaRef}; use async_trait::async_trait; use std::io::Cursor; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use std::time::Duration; pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader; @@ -54,7 +54,10 @@ pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader; /// or any future backend implementation. #[derive(Debug)] pub(crate) struct ResultReaderFactory { - client: Arc, + /// Weak because the transport owns this factory: a strong reference + /// would form a cycle that keeps the transport, its HTTP client and its + /// runtime handle alive after the session closes. + client: Weak, http_client: Arc, config: CloudFetchConfig, post_process_options: PostProcessOptions, @@ -64,7 +67,7 @@ pub(crate) struct ResultReaderFactory { impl ResultReaderFactory { /// Create a new result reader factory. pub(crate) fn new( - client: Arc, + client: Weak, http_client: Arc, config: CloudFetchConfig, mut post_process_options: PostProcessOptions, @@ -81,6 +84,15 @@ impl ResultReaderFactory { } } + /// Readers hold a strong reference so an open result stream keeps the + /// transport alive for its own chunk fetches. + fn transport(&self) -> Result> { + self.client.upgrade().ok_or_else(|| { + Error::invalid_state() + .message("transport was dropped before the result reader was created") + }) + } + /// Create a reader from a statement execution response. /// /// Automatically selects CloudFetch, inline, or other reader based @@ -541,7 +553,7 @@ impl ResultReaderFactory { // out the per-link field yet — see // `SeaChunkLinkFetcher::decode_continuation`. let fetcher = SeaChunkLinkFetcher::new( - self.client.clone(), + self.transport()?, statement_id.to_string(), external_links, total_chunk_count, @@ -623,7 +635,7 @@ impl ResultReaderFactory { let source: Arc = Arc::new(AttributedInlineChunkSource { - client: Arc::clone(&self.client), + client: self.transport()?, session_attribution, }); let provider = InlineStreamingProvider::new( @@ -2098,20 +2110,23 @@ mod tests { /// Build a `ResultReaderFactory` against the panicking stub /// transport. Used by control-flow tests that don't fire any - /// RPC. - fn factory_for_control_flow_test() -> ResultReaderFactory { + /// RPC. The factory only holds the transport weakly, so callers + /// must keep the returned transport alive for the test. + fn factory_for_control_flow_test() -> (ResultReaderFactory, Arc) { let http_client = Arc::new( DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(), ); let runtime = tokio::runtime::Handle::current(); - ResultReaderFactory::new( - Arc::new(PanickingTransport), + let transport: Arc = Arc::new(PanickingTransport); + let factory = ResultReaderFactory::new( + Arc::downgrade(&transport), http_client, CloudFetchConfig::default(), PostProcessOptions::default(), GeospatialResultRepresentation::String, runtime, - ) + ); + (factory, transport) } fn ok_status() -> StatementStatus { @@ -2152,7 +2167,7 @@ mod tests { /// result after the first chunk. #[tokio::test] async fn rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), @@ -2192,7 +2207,7 @@ mod tests { /// `total_chunk_count`. #[tokio::test] async fn rollout_guard_does_not_fire_on_genuinely_single_chunk() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), @@ -2229,7 +2244,7 @@ mod tests { /// to 0 would silently corrupt the next-fetch row_offset. #[tokio::test] async fn initial_response_requires_row_count_when_streaming() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), @@ -2263,7 +2278,7 @@ mod tests { #[tokio::test] async fn initial_response_requires_chunk_index_when_streaming() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), @@ -2310,7 +2325,7 @@ mod tests { /// rather than a silent pass. #[tokio::test] async fn zero_chunk_count_short_circuits_to_empty_reader() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), @@ -2343,7 +2358,7 @@ mod tests { /// of the field is not mis-read as `Some(0)`. #[tokio::test] async fn absent_total_chunk_count_falls_through() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), @@ -2367,7 +2382,7 @@ mod tests { /// it's not the manifest-driven `EmptyReader` path. #[tokio::test] async fn non_zero_total_chunk_count_does_not_short_circuit() { - let factory = factory_for_control_flow_test(); + let (factory, _transport) = factory_for_control_flow_test(); let response = ExecuteResponse { statement_id: "stmt-1".to_string(), status: ok_status(), diff --git a/src/session.rs b/src/session.rs index 1a64a209..152897f0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -384,11 +384,10 @@ impl Session { http_client.auth_header()?; http_client.auth_extra_headers()?; - // 3. Transport. Two-phase: SeaRestTransport needs an - // Arc to build the result-reader factory, - // which in turn needs to be set on the transport via - // OnceLock::set. So: construct, wrap in Arc, build factory, - // install factory. + // 3. Transport. Two-phase: the result-reader factory needs a + // reference back to the transport, which owns the factory via + // OnceLock::set. So: construct, wrap in Arc, build the factory + // from a Weak (a strong Arc would leak the pair), install it. let defaults = config.defaults.clone().unwrap_or_default(); let transport_config = TransportConfig { // Thread the connection-level CloudFetch toggle onto the @@ -406,7 +405,7 @@ impl Session { transport_config, )); let reader_factory = ResultReaderFactory::new( - sea.clone() as Arc, + Arc::::downgrade(&sea), http_client.clone(), result_to_cloudfetch_config(&config.result), result_to_post_process_options(&config.result), @@ -2202,6 +2201,48 @@ mod is_open_tests { ); } + /// Closing a session must free its transport. The transport owns the + /// HTTP client and tokio runtime handles; when a binding runs one + /// runtime per session (PyO3), a leaked transport keeps that + /// runtime's epoll/eventfd descriptors open until the process hits + /// its FD limit. + #[tokio::test] + async fn close_releases_transport() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-release","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-release")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .open() + .await + .expect("session must open"); + let transport = Arc::downgrade(session.inner.transport()); + + session.close().await.expect("session must close"); + + assert!( + transport.upgrade().is_none(), + "transport must be dropped once the session is closed" + ); + } + /// `Session::test_connection` round-trips a `SELECT 1` and returns /// `Ok(())` when the server responds. Pins that the probe actually /// issues a statement (POST /statements) rather than being a local