Skip to content

Commit 27fdfff

Browse files
cathleenyIsaac
authored andcommitted
fix(session): free transport before returning the HTTP pool
Dependency from PR #434 (e8920d8), adapted to current main. Exclusive HTTP-pool checkout needs the transport-reader cycle broken so closed sessions can return their clients. Signed-off-by: cathleeny <58714163+cathleeny@users.noreply.github.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 5e0bdb8 commit 27fdfff

3 files changed

Lines changed: 78 additions & 21 deletions

File tree

‎src/client/sea.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ fn timeout_query_id(params: &ExecuteParams) -> Option<String> {
171171
///
172172
/// This client implements the `Transport` trait using REST endpoints.
173173
/// The `reader_factory` is set after construction via `set_reader_factory()` because
174-
/// `ResultReaderFactory` needs `Arc<dyn Transport>` which requires wrapping
174+
/// `ResultReaderFactory` needs a `Weak<dyn Transport>`, which requires wrapping
175175
/// `SeaRestTransport` in `Arc` first.
176176
pub(crate) struct SeaRestTransport {
177177
http_client: Arc<DatabricksHttpClient>,
@@ -208,7 +208,7 @@ impl SeaRestTransport {
208208
///
209209
/// After construction, call `set_reader_factory()` to enable result reader creation.
210210
/// This two-step initialization is required because `ResultReaderFactory` needs
211-
/// `Arc<dyn Transport>`, which is only available after wrapping in `Arc`.
211+
/// `Weak<dyn Transport>`, which is only available after wrapping in `Arc`.
212212
pub fn new(
213213
http_client: Arc<DatabricksHttpClient>,
214214
host: impl Into<String>,
@@ -1910,7 +1910,7 @@ mod tests {
19101910
));
19111911
let runtime_handle = tokio::runtime::Handle::current();
19121912
let reader_factory = ResultReaderFactory::new(
1913-
transport.clone() as Arc<dyn Transport>,
1913+
Arc::<SeaRestTransport>::downgrade(&transport),
19141914
http_client,
19151915
CloudFetchConfig::default(),
19161916
PostProcessOptions::default(),

‎src/reader/mod.rs‎

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ use arrow_ipc::reader::StreamReader;
4242
use arrow_schema::{ArrowError, Field, Schema, SchemaRef};
4343
use async_trait::async_trait;
4444
use std::io::Cursor;
45-
use std::sync::Arc;
45+
use std::sync::{Arc, Weak};
4646
use std::time::Duration;
4747

4848
pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader;
@@ -54,7 +54,10 @@ pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader;
5454
/// or any future backend implementation.
5555
#[derive(Debug)]
5656
pub(crate) struct ResultReaderFactory {
57-
client: Arc<dyn Transport>,
57+
/// Weak because the transport owns this factory: a strong reference
58+
/// would form a cycle that keeps the transport, its HTTP client and its
59+
/// runtime handle alive after the session closes.
60+
client: Weak<dyn Transport>,
5861
http_client: Arc<DatabricksHttpClient>,
5962
config: CloudFetchConfig,
6063
post_process_options: PostProcessOptions,
@@ -64,7 +67,7 @@ pub(crate) struct ResultReaderFactory {
6467
impl ResultReaderFactory {
6568
/// Create a new result reader factory.
6669
pub(crate) fn new(
67-
client: Arc<dyn Transport>,
70+
client: Weak<dyn Transport>,
6871
http_client: Arc<DatabricksHttpClient>,
6972
config: CloudFetchConfig,
7073
mut post_process_options: PostProcessOptions,
@@ -81,6 +84,15 @@ impl ResultReaderFactory {
8184
}
8285
}
8386

87+
/// Readers hold a strong reference so an open result stream keeps the
88+
/// transport alive for its own chunk fetches.
89+
fn transport(&self) -> Result<Arc<dyn Transport>> {
90+
self.client.upgrade().ok_or_else(|| {
91+
Error::invalid_state()
92+
.message("transport was dropped before the result reader was created")
93+
})
94+
}
95+
8496
/// Create a reader from a statement execution response.
8597
///
8698
/// Automatically selects CloudFetch, inline, or other reader based
@@ -546,7 +558,7 @@ impl ResultReaderFactory {
546558
// out the per-link field yet — see
547559
// `SeaChunkLinkFetcher::decode_continuation`.
548560
let fetcher = SeaChunkLinkFetcher::new(
549-
self.client.clone(),
561+
self.transport()?,
550562
statement_id.to_string(),
551563
external_links,
552564
total_chunk_count,
@@ -628,7 +640,7 @@ impl ResultReaderFactory {
628640

629641
let source: Arc<dyn crate::reader::inline::InlineChunkSource> =
630642
Arc::new(AttributedInlineChunkSource {
631-
client: Arc::clone(&self.client),
643+
client: self.transport()?,
632644
session_attribution,
633645
});
634646
let provider = InlineStreamingProvider::new(
@@ -2103,20 +2115,23 @@ mod tests {
21032115

21042116
/// Build a `ResultReaderFactory` against the panicking stub
21052117
/// transport. Used by control-flow tests that don't fire any
2106-
/// RPC.
2107-
fn factory_for_control_flow_test() -> ResultReaderFactory {
2118+
/// RPC. The factory only holds the transport weakly, so callers
2119+
/// must keep the returned transport alive for the test.
2120+
fn factory_for_control_flow_test() -> (ResultReaderFactory, Arc<dyn Transport>) {
21082121
let http_client = Arc::new(
21092122
DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(),
21102123
);
21112124
let runtime = tokio::runtime::Handle::current();
2112-
ResultReaderFactory::new(
2113-
Arc::new(PanickingTransport),
2125+
let transport: Arc<dyn Transport> = Arc::new(PanickingTransport);
2126+
let factory = ResultReaderFactory::new(
2127+
Arc::downgrade(&transport),
21142128
http_client,
21152129
CloudFetchConfig::default(),
21162130
PostProcessOptions::default(),
21172131
GeospatialResultRepresentation::String,
21182132
runtime,
2119-
)
2133+
);
2134+
(factory, transport)
21202135
}
21212136

21222137
fn ok_status() -> StatementStatus {
@@ -2157,7 +2172,7 @@ mod tests {
21572172
/// result after the first chunk.
21582173
#[tokio::test]
21592174
async fn rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index() {
2160-
let factory = factory_for_control_flow_test();
2175+
let (factory, _transport) = factory_for_control_flow_test();
21612176
let response = ExecuteResponse {
21622177
statement_id: "stmt-1".to_string(),
21632178
status: ok_status(),
@@ -2197,7 +2212,7 @@ mod tests {
21972212
/// `total_chunk_count`.
21982213
#[tokio::test]
21992214
async fn rollout_guard_does_not_fire_on_genuinely_single_chunk() {
2200-
let factory = factory_for_control_flow_test();
2215+
let (factory, _transport) = factory_for_control_flow_test();
22012216
let response = ExecuteResponse {
22022217
statement_id: "stmt-1".to_string(),
22032218
status: ok_status(),
@@ -2234,7 +2249,7 @@ mod tests {
22342249
/// to 0 would silently corrupt the next-fetch row_offset.
22352250
#[tokio::test]
22362251
async fn initial_response_requires_row_count_when_streaming() {
2237-
let factory = factory_for_control_flow_test();
2252+
let (factory, _transport) = factory_for_control_flow_test();
22382253
let response = ExecuteResponse {
22392254
statement_id: "stmt-1".to_string(),
22402255
status: ok_status(),
@@ -2268,7 +2283,7 @@ mod tests {
22682283

22692284
#[tokio::test]
22702285
async fn initial_response_requires_chunk_index_when_streaming() {
2271-
let factory = factory_for_control_flow_test();
2286+
let (factory, _transport) = factory_for_control_flow_test();
22722287
let response = ExecuteResponse {
22732288
statement_id: "stmt-1".to_string(),
22742289
status: ok_status(),
@@ -2315,7 +2330,7 @@ mod tests {
23152330
/// rather than a silent pass.
23162331
#[tokio::test]
23172332
async fn zero_chunk_count_short_circuits_to_empty_reader() {
2318-
let factory = factory_for_control_flow_test();
2333+
let (factory, _transport) = factory_for_control_flow_test();
23192334
let response = ExecuteResponse {
23202335
statement_id: "stmt-1".to_string(),
23212336
status: ok_status(),
@@ -2348,7 +2363,7 @@ mod tests {
23482363
/// of the field is not mis-read as `Some(0)`.
23492364
#[tokio::test]
23502365
async fn absent_total_chunk_count_falls_through() {
2351-
let factory = factory_for_control_flow_test();
2366+
let (factory, _transport) = factory_for_control_flow_test();
23522367
let response = ExecuteResponse {
23532368
statement_id: "stmt-1".to_string(),
23542369
status: ok_status(),
@@ -2372,7 +2387,7 @@ mod tests {
23722387
/// it's not the manifest-driven `EmptyReader` path.
23732388
#[tokio::test]
23742389
async fn non_zero_total_chunk_count_does_not_short_circuit() {
2375-
let factory = factory_for_control_flow_test();
2390+
let (factory, _transport) = factory_for_control_flow_test();
23762391
let response = ExecuteResponse {
23772392
statement_id: "stmt-1".to_string(),
23782393
status: ok_status(),

‎src/session.rs‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ impl Session {
401401
transport_config,
402402
));
403403
let reader_factory = ResultReaderFactory::new(
404-
sea.clone() as Arc<dyn Transport>,
404+
Arc::<SeaRestTransport>::downgrade(&sea),
405405
http_client.clone(),
406406
result_to_cloudfetch_config(&config.result),
407407
result_to_post_process_options(&config.result),
@@ -2220,6 +2220,48 @@ mod is_open_tests {
22202220
);
22212221
}
22222222

2223+
/// Closing a session must free its transport. The transport owns the
2224+
/// HTTP client and tokio runtime handles; when a binding runs one
2225+
/// runtime per session (PyO3), a leaked transport keeps that
2226+
/// runtime's epoll/eventfd descriptors open until the process hits
2227+
/// its FD limit.
2228+
#[tokio::test]
2229+
async fn close_releases_transport() {
2230+
let server = MockServer::start().await;
2231+
Mock::given(method("POST"))
2232+
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
2233+
.respond_with(
2234+
ResponseTemplate::new(200)
2235+
.set_body_string(r#"{"session_id":"sess-release","warehouse_id":"test_wh"}"#),
2236+
)
2237+
.mount(&server)
2238+
.await;
2239+
Mock::given(method("DELETE"))
2240+
.and(path("/api/2.0/sql/sessions/sess-release"))
2241+
.respond_with(ResponseTemplate::new(200))
2242+
.expect(1)
2243+
.mount(&server)
2244+
.await;
2245+
2246+
let session = Session::builder()
2247+
.http_path(server.uri(), "/sql/1.0/warehouses/test_wh")
2248+
.auth(AuthConfig::Pat {
2249+
token: "dapi_test_token".into(),
2250+
identity_federation_client_id: None,
2251+
})
2252+
.open()
2253+
.await
2254+
.expect("session must open");
2255+
let transport = Arc::downgrade(session.inner.transport());
2256+
2257+
session.close().await.expect("session must close");
2258+
2259+
assert!(
2260+
transport.upgrade().is_none(),
2261+
"transport must be dropped once the session is closed"
2262+
);
2263+
}
2264+
22232265
/// `Session::test_connection` round-trips a `SELECT 1` and returns
22242266
/// `Ok(())` when the server responds. Pins that the probe actually
22252267
/// issues a statement (POST /statements) rather than being a local

0 commit comments

Comments
 (0)