diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8577a424..2679ab73 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -34,6 +34,7 @@ changes go in their respective binding's NEXT_CHANGELOG. - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. - A timed-out or reset CloudFetch download no longer writes the presigned URL's signature (`sig=`, `X-Amz-Signature`) to the log or the returned error. The request URL in those messages now ends at the path, and debug request lines stop at `?`. - Closing an OAuth session (M2M, M2M private key, U2M or Azure service principal) now frees its HTTP client and auth provider. The provider held the HTTP client strongly while the client owned the provider, so the pair and the provider's tokio runtime handle leaked for every closed session. +- 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 b94f6d23..08abede8 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, @@ -1910,7 +1910,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 33e7816d..fd616540 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 @@ -546,7 +558,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, @@ -628,7 +640,7 @@ impl ResultReaderFactory { let source: Arc = Arc::new(AttributedInlineChunkSource { - client: Arc::clone(&self.client), + client: self.transport()?, session_attribution, }); let provider = InlineStreamingProvider::new( @@ -2103,20 +2115,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 { @@ -2157,7 +2172,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(), @@ -2197,7 +2212,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(), @@ -2234,7 +2249,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(), @@ -2268,7 +2283,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(), @@ -2315,7 +2330,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(), @@ -2348,7 +2363,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(), @@ -2372,7 +2387,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 2c1bdd79..ac2f462f 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 { cloudfetch_enabled: config.result.cloudfetch_enabled, @@ -401,7 +400,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), @@ -2220,6 +2219,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