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
127 changes: 73 additions & 54 deletions src/auth/oauth/m2m.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ use crate::auth::oauth::token_store::TokenStore;
use crate::auth::AuthProvider;
use crate::client::http::DatabricksHttpClient;
use crate::kernel_error::{Error, Result};
use crate::util::runtime::block_on_in_runtime;
use oauth2::basic::BasicClient;
use oauth2::{AuthUrl, ClientId, ClientSecret, Scope, TokenResponse, TokenUrl};
use std::sync::Arc;
use tokio::runtime::Handle as RuntimeHandle;

/// OAuth provider for M2M (Machine-to-Machine) authentication.
///
Expand Down Expand Up @@ -90,6 +92,12 @@ pub struct ClientCredentialsProvider {
http_client: Arc<DatabricksHttpClient>,
/// OAuth scopes to request (typically "all-apis")
scopes: Vec<String>,
/// Tokio runtime handle captured from the constructing context;
/// used to drive the async token exchange from the sync
/// `get_auth_header` trait method safely whether or not the
/// caller is already inside a runtime (see
/// `crate::util::runtime::block_on_in_runtime`).
runtime_handle: RuntimeHandle,
}

impl ClientCredentialsProvider {
Expand Down Expand Up @@ -207,6 +215,14 @@ impl ClientCredentialsProvider {
token_store: TokenStore::new(),
http_client,
scopes,
// `new_with_full_config` is `async`, so we're guaranteed
// to be inside a tokio runtime here. Capture that handle
// so `get_auth_header` can dispatch correctly later via
// `block_on_in_runtime`, even when the caller has
// wrapped the kernel in its own outer `block_on` (e.g.
// the PyO3 binding) or eventually drives auth from a
// non-tokio thread (e.g. the C ABI shim).
runtime_handle: RuntimeHandle::current(),
})
}
}
Expand Down Expand Up @@ -238,61 +254,64 @@ impl AuthProvider for ClientCredentialsProvider {
let scopes = self.scopes.clone();

// Get or refresh token via TokenStore
let runtime_handle = self.runtime_handle.clone();
let token = self.token_store.get_or_refresh(move || {
// Execute async token fetch within the runtime
// Use block_in_place to avoid blocking the runtime if we're in one,
// and get the handle to block_on the async operation
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(async {
// Build the OAuth client
let oauth_client = BasicClient::new(ClientId::new(client_id))
.set_client_secret(ClientSecret::new(client_secret))
.set_auth_uri(AuthUrl::new(auth_endpoint).map_err(|e| {
Error::invalid_argument()
.message(format!("Invalid authorization endpoint URL: {}", e))
})?)
.set_token_uri(TokenUrl::new(token_endpoint).map_err(|e| {
Error::invalid_argument()
.message(format!("Invalid token endpoint URL: {}", e))
})?);

// Build the token request
let mut token_request = oauth_client.exchange_client_credentials();
for scope in &scopes {
token_request = token_request.add_scope(Scope::new(scope.clone()));
}

// Execute the token exchange using inner reqwest client
let token_response = token_request
.request_async(http_client.inner())
.await
.map_err(|e| {
Error::io()
.message(format!("M2M token exchange failed: {}", e))
.context("client credentials grant")
})?;

// Convert to OAuthToken
let access_token = token_response.access_token().secret().to_string();
let token_type = token_response.token_type().as_ref().to_string();
let expires_in = token_response
.expires_in()
.map(|d| d.as_secs() as i64)
.unwrap_or(3600);

let scopes_result = token_response
.scopes()
.map(|s| s.iter().map(|scope| scope.to_string()).collect())
.unwrap_or_else(|| scopes.clone());

Ok(OAuthToken::new(
access_token,
token_type,
expires_in,
None, // No refresh token for M2M
scopes_result,
))
})
// Execute the async token fetch via the kernel's
// captured runtime handle. `block_on_in_runtime`
// dispatches on `Handle::try_current()`: it uses
// `block_in_place` when called from inside a runtime
// (e.g. driven by the PyO3 wrapper), and falls back to
// a direct `block_on` when called from a plain thread
// (e.g. the future C ABI shim). See `crate::util::runtime`.
block_on_in_runtime(&runtime_handle, async {
// Build the OAuth client
let oauth_client = BasicClient::new(ClientId::new(client_id))
.set_client_secret(ClientSecret::new(client_secret))
.set_auth_uri(AuthUrl::new(auth_endpoint).map_err(|e| {
Error::invalid_argument()
.message(format!("Invalid authorization endpoint URL: {}", e))
})?)
.set_token_uri(TokenUrl::new(token_endpoint).map_err(|e| {
Error::invalid_argument()
.message(format!("Invalid token endpoint URL: {}", e))
})?);

// Build the token request
let mut token_request = oauth_client.exchange_client_credentials();
for scope in &scopes {
token_request = token_request.add_scope(Scope::new(scope.clone()));
}

// Execute the token exchange using inner reqwest client
let token_response = token_request
.request_async(http_client.inner())
.await
.map_err(|e| {
Error::io()
.message(format!("M2M token exchange failed: {}", e))
.context("client credentials grant")
})?;

// Convert to OAuthToken
let access_token = token_response.access_token().secret().to_string();
let token_type = token_response.token_type().as_ref().to_string();
let expires_in = token_response
.expires_in()
.map(|d| d.as_secs() as i64)
.unwrap_or(3600);

let scopes_result = token_response
.scopes()
.map(|s| s.iter().map(|scope| scope.to_string()).collect())
.unwrap_or_else(|| scopes.clone());

Ok(OAuthToken::new(
access_token,
token_type,
expires_in,
None, // No refresh token for M2M
scopes_result,
))
})
})?;

Expand Down
24 changes: 20 additions & 4 deletions src/auth/oauth/u2m.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@ use crate::auth::oauth::token_store::TokenStore;
use crate::auth::AuthProvider;
use crate::client::http::DatabricksHttpClient;
use crate::kernel_error::{Error, Result};
use crate::util::runtime::block_on_in_runtime;
use oauth2::basic::BasicClient;
use oauth2::{
AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, RefreshToken,
Scope, TokenResponse, TokenUrl,
};
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle as RuntimeHandle;

/// Default callback server port for OAuth redirects.
const DEFAULT_CALLBACK_PORT: u16 = 8020;
Expand Down Expand Up @@ -112,6 +114,12 @@ pub struct AuthorizationCodeProvider {
callback_timeout: Duration,
/// Whether to open browser automatically (set to false in tests)
open_browser: bool,
/// Tokio runtime handle captured from the constructing context;
/// used to drive the async token exchange from the sync
/// `get_auth_header` trait method safely whether or not the
/// caller is already inside a runtime (see
/// `crate::util::runtime::block_on_in_runtime`).
runtime_handle: RuntimeHandle,
}

impl AuthorizationCodeProvider {
Expand Down Expand Up @@ -243,6 +251,11 @@ impl AuthorizationCodeProvider {
callback_port,
callback_timeout,
open_browser: true,
// `new_with_full_config` is `async`, so we're guaranteed
// to be inside a tokio runtime here. Capture that handle
// so `get_auth_header` can dispatch correctly later via
// `block_on_in_runtime`.
runtime_handle: RuntimeHandle::current(),
})
}
}
Expand Down Expand Up @@ -291,10 +304,14 @@ impl AuthProvider for AuthorizationCodeProvider {
let http_client = self.http_client.clone();

// Get or refresh token via TokenStore
let runtime_handle = self.runtime_handle.clone();
let token = self.token_store.get_or_refresh(move || {
// Execute async token fetch/refresh within the runtime
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(async {
// Execute async token fetch/refresh via the kernel's
// captured runtime handle. `block_on_in_runtime`
// dispatches on `Handle::try_current()`: `block_in_place`
// inside a runtime, direct `block_on` otherwise. See
// `crate::util::runtime`.
block_on_in_runtime(&runtime_handle, async {
// Try loading from cache first
if let Some(cached_token) = TokenCache::load(&host, &client_id, &scopes) {
if let Some(ref refresh_token_str) = cached_token.refresh_token {
Expand Down Expand Up @@ -464,7 +481,6 @@ impl AuthProvider for AuthorizationCodeProvider {
TokenCache::save(&host, &client_id, &scopes, &token);

Ok(token)
})
})
})?;

Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ pub mod kernel_error;
pub mod metadata_v0;
pub mod result_stream;
pub mod session;
pub(crate) mod util;

// Custom C ABI for ODBC / Go consumers (skeleton).
pub mod ffi;
Expand Down
5 changes: 3 additions & 2 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use crate::reader::cloudfetch::streaming_provider::StreamingCloudFetchProvider;
use crate::reader::inline::InlineArrowProvider;
use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink};
use crate::types::sea::{CompressionCodec, ResultManifest, StatementState};
use crate::util::runtime::block_on_in_runtime;
use arrow_array::RecordBatch;
use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef};
use std::sync::Arc;
Expand Down Expand Up @@ -318,11 +319,11 @@ impl CloudFetchResultReader {

impl ResultReader for CloudFetchResultReader {
fn schema(&self) -> Result<SchemaRef> {
self.runtime_handle.block_on(self.provider.get_schema())
block_on_in_runtime(&self.runtime_handle, self.provider.get_schema())
}

fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
self.runtime_handle.block_on(self.provider.next_batch())
block_on_in_runtime(&self.runtime_handle, self.provider.next_batch())
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/util/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (c) 2026 Databricks, Inc.
//
// Licensed 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.

//! Internal kernel utilities shared across modules.

pub(crate) mod runtime;
59 changes: 59 additions & 0 deletions src/util/runtime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2026 Databricks, Inc.
//
// Licensed 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.

//! Tokio runtime bridging utilities for sync ↔ async boundaries.

/// Bridge a sync call site to an async kernel operation, safely
/// whether or not the caller is already inside a tokio runtime.
///
/// Naively calling `runtime_handle.block_on(fut)` works when invoked
/// from outside any tokio runtime, but panics ("Cannot start a
/// runtime from within a runtime") when the kernel is being driven
/// by a wrapper that already owns a `block_on` higher up the stack —
/// exactly what the PyO3 binding does for every kernel call (see
/// issue #19).
///
/// `tokio::task::block_in_place` tells the runtime "I'm about to do
/// something blocking; move other tasks to a different worker
/// thread." After that, `runtime_handle.block_on(fut)` is safe
/// because the runtime considers this thread off-budget. We pass the
/// captured handle (not `Handle::current()`) so the function honors
/// the documented invariant that callers thread the kernel's session
/// handle through to here.
///
/// **Requires a multi-threaded runtime when called from inside a
/// runtime context.** `block_in_place` panics on current-thread
/// runtimes. The kernel's session runtime is multi-thread (see
/// `Builder::new_multi_thread` in the PyO3 wrapper and the
/// `flavor = "multi_thread"` annotation on the regression test for
/// issue #19), and any caller driving the kernel from a runtime
/// context should also be on multi-thread for the same concurrent-IO
/// reasons.
pub(crate) fn block_on_in_runtime<F>(runtime_handle: &tokio::runtime::Handle, fut: F) -> F::Output
where
F: std::future::Future,
{
if tokio::runtime::Handle::try_current().is_ok() {
// Inside a runtime: escape via block_in_place + the
// captured handle.
tokio::task::block_in_place(|| runtime_handle.block_on(fut))
} else {
// Outside any runtime (direct Rust-crate use, e.g. the
// ODBC C ABI shim's sync entry points): block_on the
// captured handle directly. `block_in_place` would panic
// on a current-thread runtime, so we keep the old path for
// callers that aren't already in a runtime.
runtime_handle.block_on(fut)
}
}
40 changes: 40 additions & 0 deletions tests/v0_execute_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,3 +402,43 @@ async fn bind_binary_typed_value_is_rejected_at_execute_time() {
assert!(err.message.contains("unhex"), "{}", err.message);
session.close().await.expect("session close");
}

/// Repro for issue #19: `CloudFetchResultReader::next_batch` calls
/// `runtime_handle.block_on` from a sync trait method. When the
/// kernel is driven from inside an enclosing tokio runtime (e.g.
/// the PyO3 wrapper's `runtime.block_on`, or a `#[tokio::test]`
/// here), the inner `block_on` is nested under the same runtime
/// and tokio panics with "Cannot start a runtime from within a
/// runtime."
///
/// `range(100000)` is too small to flip the server to CloudFetch
/// disposition (it inlines the Arrow stream), so the existing
/// `multi_batch_range_succeeds` test never reaches the
/// `block_on` path. `range(1000000)` reliably triggers external
/// links on Dogfood.
///
/// Gated to `flavor = "multi_thread"` because the eventual fix
/// uses `tokio::task::block_in_place`, which is a no-op on
/// current-thread runtimes. The PyO3 wrapper is multi-thread, so
/// matching that here is the realistic shape.
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn cloudfetch_drain_does_not_nest_block_on() {
let session = live_session().await;
let mut stmt = session.statement();
// Large enough to force external-links disposition (the
// CloudFetchResultReader path) on Dogfood. If a future
// server-side change moves the inline/external threshold,
// bump this.
stmt.spec().sql("SELECT * FROM range(1000000)");
let mut exec = stmt.execute().await.expect("execute range(1000000)");

let rows = drain_rows(exec.result_stream_mut()).await;
assert_eq!(
rows, 1_000_000,
"expected 1M rows; if this drain panicked with \
'Cannot start a runtime from within a runtime' the fix has regressed"
);
exec.close().await.expect("close");
session.close().await.expect("session close");
}