Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ fn timeout_query_id(params: &ExecuteParams) -> Option<String> {
///
/// This client implements the `Transport` trait using REST endpoints.
/// The `reader_factory` is set after construction via `set_reader_factory()` because
/// `ResultReaderFactory` needs `Arc<dyn Transport>` which requires wrapping
/// `ResultReaderFactory` needs a `Weak<dyn Transport>`, which requires wrapping
/// `SeaRestTransport` in `Arc` first.
pub(crate) struct SeaRestTransport {
http_client: Arc<DatabricksHttpClient>,
Expand Down Expand Up @@ -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<dyn Transport>`, which is only available after wrapping in `Arc`.
/// `Weak<dyn Transport>`, which is only available after wrapping in `Arc`.
pub fn new(
http_client: Arc<DatabricksHttpClient>,
host: impl Into<String>,
Expand Down Expand Up @@ -1910,7 +1910,7 @@ mod tests {
));
let runtime_handle = tokio::runtime::Handle::current();
let reader_factory = ResultReaderFactory::new(
transport.clone() as Arc<dyn Transport>,
Arc::<SeaRestTransport>::downgrade(&transport),
http_client,
CloudFetchConfig::default(),
PostProcessOptions::default(),
Expand Down
49 changes: 32 additions & 17 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -54,7 +54,10 @@ pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader;
/// or any future backend implementation.
#[derive(Debug)]
pub(crate) struct ResultReaderFactory {
client: Arc<dyn Transport>,
/// 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<dyn Transport>,
http_client: Arc<DatabricksHttpClient>,
config: CloudFetchConfig,
post_process_options: PostProcessOptions,
Expand All @@ -64,7 +67,7 @@ pub(crate) struct ResultReaderFactory {
impl ResultReaderFactory {
/// Create a new result reader factory.
pub(crate) fn new(
client: Arc<dyn Transport>,
client: Weak<dyn Transport>,
http_client: Arc<DatabricksHttpClient>,
config: CloudFetchConfig,
mut post_process_options: PostProcessOptions,
Expand All @@ -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<Arc<dyn Transport>> {
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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -628,7 +640,7 @@ impl ResultReaderFactory {

let source: Arc<dyn crate::reader::inline::InlineChunkSource> =
Arc::new(AttributedInlineChunkSource {
client: Arc::clone(&self.client),
client: self.transport()?,
session_attribution,
});
let provider = InlineStreamingProvider::new(
Expand Down Expand Up @@ -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<dyn Transport>) {
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<dyn Transport> = 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 {
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand All @@ -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(),
Expand Down
53 changes: 47 additions & 6 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,11 +384,10 @@ impl Session {
http_client.auth_header()?;
http_client.auth_extra_headers()?;

// 3. Transport. Two-phase: SeaRestTransport needs an
// Arc<dyn Transport> 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,
Expand All @@ -401,7 +400,7 @@ impl Session {
transport_config,
));
let reader_factory = ResultReaderFactory::new(
sea.clone() as Arc<dyn Transport>,
Arc::<SeaRestTransport>::downgrade(&sea),
http_client.clone(),
result_to_cloudfetch_config(&config.result),
result_to_post_process_options(&config.result),
Expand Down Expand Up @@ -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
Expand Down
Loading