diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 28a2d4ab..c18d95f8 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,16 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Cooperative cancel token for the blocking C-ABI entry points + (`kernel_cancel_token_new` / `_cancel` / `_is_cancelled` / `_free`), plus + cancellable variants `kernel_session_open_cancellable` and + `kernel_result_stream_next_batch_cancellable`. A host creates a token before a + blocking call, passes it in, and fires it from another thread when its + deadline elapses; the call drops its in-flight request future (a real + `reqwest` abort) and returns `Cancelled`. A null token is byte-for-byte the + plain path, so existing symbols and the default path are unchanged. Additive + only — ABI unchanged. + ### Updated ### Fixed diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index cf42e4e6..644416cf 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -213,6 +213,15 @@ typedef struct kernel_result_stream_t kernel_result_stream_t; * cancels the LATER query. Use one per execute (new before execute, free after * it returns). */ typedef struct kernel_statement_canceller_t kernel_statement_canceller_t; +/* Cooperative cancel token for the blocking `*_cancellable` entry points + * (kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable). + * Create one before a blocking call, pass it in, and fire it from ANOTHER + * thread (kernel_cancel_token_cancel) when the caller's deadline elapses; the + * blocked call then drops its in-flight request future and returns + * KernelStatusCode_Cancelled. One-shot (a fired token stays fired) — create a + * fresh token per logical operation. Firing is purely local (no RPC), so it + * never blocks. See "Cooperative cancellation" below. */ +typedef struct kernel_cancel_token_t kernel_cancel_token_t; /* ─── Session config ────────────────────────────────────────────────── * @@ -313,6 +322,21 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); +/* + * Like kernel_session_open, but races the (blocking) connect against + * `cancel_token` so a host can bound a slow warehouse cold-start or a + * connect-time network partition by its own deadline. A NULL `cancel_token` + * behaves EXACTLY like kernel_session_open. If the token fires (or is already + * fired) before connect completes, the connect future is dropped — aborting + * the in-flight request — and this returns KernelStatusCode_Cancelled; `config` + * is CONSUMED on every path regardless. `cancel_token` is borrowed, not + * consumed: the caller still owns and must free it after this returns, and may + * fire it from another thread while this call is in flight. + */ +KernelStatusCode kernel_session_open_cancellable(KernelSessionConfig* config, + kernel_session_t** out, + const kernel_cancel_token_t* cancel_token); + /* Report whether a session is still OPEN (its delete has not been * initiated). Writes true/false to `*out`. LOCAL check only — no server * round-trip, so it does NOT detect a server idle-timeout or dropped @@ -476,6 +500,32 @@ KernelStatusCode kernel_statement_canceller_cancel( KernelStatusCode kernel_statement_canceller_free( kernel_statement_canceller_t* canceller); +/* ─── Cooperative cancellation (blocking-call cancel token) ──────────── + * + * The statement canceller above cancels a server-side STATEMENT (right for a + * query still executing). A cancel token cancels a blocking C-ABI CALL itself — + * connect or a stalled result-stream fetch — neither of which the statement + * canceller reaches (the server statement is already done; the stall is + * client-side). It is the generic mechanism a host uses to honour a caller + * deadline / context on the `*_cancellable` entry points. + * + * Usage: create a token, spawn a watcher on the caller's deadline/context, make + * the blocking `*_cancellable` call on the owning thread, and from the watcher + * fire kernel_cancel_token_cancel when the deadline elapses. The blocked call + * drops its in-flight request future and returns KernelStatusCode_Cancelled. + * Firing is purely local (flip an atomic, wake the waiter) — no RPC, never + * blocks. The token is ONE-SHOT (a fired token stays fired), so create a fresh + * one per logical operation. Safe to fire from a different thread than the + * blocking call (that is the intended use); do NOT free the token until both + * the blocking call and any in-flight cancel have returned. + */ +KernelStatusCode kernel_cancel_token_new(kernel_cancel_token_t** out); +KernelStatusCode kernel_cancel_token_cancel(kernel_cancel_token_t* token); +/* Report whether the token has been fired (writes true/false to *out). Local + * atomic read — no RPC, never blocks. Symmetric with kernel_session_is_open. */ +KernelStatusCode kernel_cancel_token_is_cancelled(const kernel_cancel_token_t* token, bool* out); +KernelStatusCode kernel_cancel_token_free(kernel_cancel_token_t* token); + /* ─── Executed statement (sync) ───────────────────────────────────────*/ /* @@ -523,6 +573,21 @@ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, struct ArrowSchema* out_schema); +/* + * Like kernel_result_stream_next_batch, but races the (blocking) fetch against + * `cancel_token` so a host can interrupt a HUNG CloudFetch chunk (a wedged S3 / + * pre-signed-URL GET) instead of blocking on it forever. A NULL `cancel_token` + * behaves EXACTLY like kernel_result_stream_next_batch. If the token fires + * before the batch is ready, the fetch future is dropped (aborting the in-flight + * download) and this returns KernelStatusCode_Cancelled; the stream handle stays + * valid and owned by the caller (close it with kernel_result_stream_close as + * usual — a cancelled fetch neither consumes nor frees it). `cancel_token` is + * borrowed and safe to fire from another thread while this call is in flight + * (see kernel_session_open_cancellable). + */ +KernelStatusCode kernel_result_stream_next_batch_cancellable( + kernel_result_stream_t* stream, struct ArrowArray* out_array, + struct ArrowSchema* out_schema, const kernel_cancel_token_t* cancel_token); KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); /* ─── Metadata ──────────────────────────────────────────────────────── diff --git a/src/c_abi/cancel.rs b/src/c_abi/cancel.rs new file mode 100644 index 00000000..83f1f28a --- /dev/null +++ b/src/c_abi/cancel.rs @@ -0,0 +1,245 @@ +// 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. + +//! Generic cooperative cancel token for the blocking C-ABI entry points. +//! +//! The v0 C ABI drives every async operation through +//! [`block_on_ffi`](crate::c_abi::block_on_ffi), which blocks the calling +//! (native) thread until the future completes. That thread cannot observe a +//! host-side deadline/cancel (a Go `context.Context`, an ODBC `SQLCancel`) +//! mid-call, so a hung connect or a hung result-stream fetch blocks the caller +//! past its deadline — the runtime-contract gap the host drivers track as +//! mid-fetch (hung CloudFetch chunk) and session-connect deadlines. +//! +//! This module adds one primitive that closes both: a [`kernel_cancel_token_t`] +//! the host creates before a blocking call, passes into a `*_cancellable` +//! variant of that call, and fires from *another* thread when its deadline +//! elapses. The cancellable entry point runs its future under +//! [`block_on_ffi_cancellable`](crate::c_abi::block_on_ffi_cancellable), which +//! races the future against the token and — on a fire — **drops the future**. +//! Because the kernel's HTTP client is `reqwest` and its futures cancel by +//! being dropped (the crate-wide model; see the CloudFetch streaming provider's +//! own [`CancellationToken`] use), dropping the future genuinely aborts the +//! in-flight request rather than merely stopping the wait. +//! +//! The token wraps [`tokio_util::sync::CancellationToken`], which is cheap to +//! clone (an `Arc` internally) and safe to fire from any thread — the same +//! shape as the statement canceller ([`kernel_statement_canceller_t`]), and for +//! the same reason (the blocking call runs on one thread, the cancel on +//! another). Unlike the statement canceller, firing is purely local (flip an +//! atomic + wake waiters); it dispatches no RPC, so it never blocks. +//! +//! One token drives at most one in-flight call at a time. Reuse across +//! sequential calls is allowed, but a token that has already been fired stays +//! fired (a `CancellationToken` is one-shot), so create a fresh token per +//! logical operation — exactly as a Go caller creates a fresh watcher per +//! `ctx`. +//! +//! [`kernel_statement_canceller_t`]: crate::c_abi::statement::kernel_statement_canceller_t +//! [`CancellationToken`]: tokio_util::sync::CancellationToken + +#![allow(non_camel_case_types)] + +use super::error::store_invalid_arg; +use super::{catch_ffi, KernelStatusCode}; +use tokio_util::sync::CancellationToken; + +/// Opaque cancel-token handle. Boxes a [`CancellationToken`] the host fires +/// from a watcher thread to interrupt a blocking `*_cancellable` C-ABI call. +#[repr(C)] +pub struct kernel_cancel_token_t { + _private: [u8; 0], +} + +/// Owned box behind a [`kernel_cancel_token_t`]. +struct CancelTokenHandle { + token: CancellationToken, +} + +/// Crate-internal: borrow the [`CancellationToken`] out of a raw handle, or +/// `None` when the handle pointer is null. The returned reference is only used +/// to `clone()` the token (a cheap `Arc` bump) into the future's `select!`, so +/// the caller keeps ownership of the box and may still fire it concurrently. +/// +/// # Safety +/// `token` must be null or a live handle from [`kernel_cancel_token_new`]. +pub(crate) unsafe fn token_ref<'a>( + token: *const kernel_cancel_token_t, +) -> Option<&'a CancellationToken> { + (token as *const CancelTokenHandle) + .as_ref() + .map(|h| &h.token) +} + +/// Create a fresh, un-fired cancel token. On success `*out` holds an owned +/// handle the caller releases with [`kernel_cancel_token_free`], and may fire +/// with [`kernel_cancel_token_cancel`] from any thread. +/// +/// # Safety +/// `out` must be a valid, writable pointer to a `kernel_cancel_token_t*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_new( + out: *mut *mut kernel_cancel_token_t, +) -> KernelStatusCode { + catch_ffi(|| { + if out.is_null() { + return store_invalid_arg("kernel_cancel_token_new: out must not be null"); + } + let handle = CancelTokenHandle { + token: CancellationToken::new(), + }; + std::ptr::write( + out, + Box::into_raw(Box::new(handle)) as *mut kernel_cancel_token_t, + ); + KernelStatusCode::Success + }) +} + +/// Fire the token, requesting cancellation of whatever blocking +/// `*_cancellable` call it was passed to. Idempotent (a `CancellationToken` is +/// one-shot; a second fire is a no-op) and safe to call concurrently with the +/// blocking call the token drives — that is the whole point: the blocking call +/// runs on one thread and this fires from another. +/// +/// Purely local: flips the token's atomic and wakes the `select!` waiting on +/// it. Dispatches no RPC, so it never blocks and never fails on a live handle. +/// +/// # Safety +/// `token` must be a live handle from [`kernel_cancel_token_new`], not yet +/// freed. It is safe to call while a `*_cancellable` call driven by this token +/// is in flight; do not [`kernel_cancel_token_free`] the handle until both this +/// call and that blocking call have returned. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_cancel( + token: *mut kernel_cancel_token_t, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (token as *const CancelTokenHandle).as_ref() else { + return store_invalid_arg("kernel_cancel_token_cancel: token must not be null"); + }; + handle.token.cancel(); + KernelStatusCode::Success + }) +} + +/// Report whether the token has been fired, writing `true`/`false` to `*out`. +/// A local read of the token's atomic — no RPC, never blocks. Symmetric with +/// [`kernel_session_is_open`](crate::c_abi::session::kernel_session_is_open); +/// lets a host (or its tests) observe the token state it set. Does not borrow +/// ownership; the caller still owns `token`. +/// +/// # Safety +/// `token` must be a live handle from [`kernel_cancel_token_new`], not yet +/// freed; `out` must be a writable `bool*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_is_cancelled( + token: *const kernel_cancel_token_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (token as *const CancelTokenHandle).as_ref() else { + return store_invalid_arg("kernel_cancel_token_is_cancelled: token must not be null"); + }; + if out.is_null() { + return store_invalid_arg("kernel_cancel_token_is_cancelled: out must not be null"); + } + std::ptr::write(out, handle.token.is_cancelled()); + KernelStatusCode::Success + }) +} + +/// Free a cancel-token handle. Does not touch any call the token drove. +/// +/// # Safety +/// `token` must have been returned by [`kernel_cancel_token_new`] and not +/// previously freed. The token is single-owner for teardown: no other thread +/// may be inside [`kernel_cancel_token_cancel`] on this handle, and no +/// `*_cancellable` call driven by it may be in flight, when it is freed. +#[no_mangle] +pub unsafe extern "C" fn kernel_cancel_token_free( + token: *mut kernel_cancel_token_t, +) -> KernelStatusCode { + catch_ffi(|| { + if token.is_null() { + return store_invalid_arg("kernel_cancel_token_free: token must not be null"); + } + drop(Box::from_raw(token as *mut CancelTokenHandle)); + KernelStatusCode::Success + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// new → cancel → free round-trips, and the borrowed token reflects the + /// fire (the property the cancellable entry points rely on). + #[test] + fn new_cancel_free_round_trip() { + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + let rc = unsafe { kernel_cancel_token_new(&mut tok) }; + assert_eq!(rc, KernelStatusCode::Success); + assert!(!tok.is_null()); + + // Not fired yet — observe via both the borrow and the C accessor. + let borrowed = unsafe { token_ref(tok) }.expect("live token"); + assert!(!borrowed.is_cancelled()); + let mut fired = true; + assert_eq!( + unsafe { kernel_cancel_token_is_cancelled(tok, &mut fired) }, + KernelStatusCode::Success + ); + assert!(!fired, "is_cancelled reports false before a fire"); + + // Fire it, then observe the flip through the borrow AND the accessor. + let rc = unsafe { kernel_cancel_token_cancel(tok) }; + assert_eq!(rc, KernelStatusCode::Success); + assert!(borrowed.is_cancelled(), "cancel() must flip the token"); + assert_eq!( + unsafe { kernel_cancel_token_is_cancelled(tok, &mut fired) }, + KernelStatusCode::Success + ); + assert!(fired, "is_cancelled reports true after a fire"); + + // Second fire is a no-op (one-shot), still Success. + let rc = unsafe { kernel_cancel_token_cancel(tok) }; + assert_eq!(rc, KernelStatusCode::Success); + + let rc = unsafe { kernel_cancel_token_free(tok) }; + assert_eq!(rc, KernelStatusCode::Success); + } + + /// Null-pointer guards on every entry point return `InvalidArgument`, + /// never crash. + #[test] + fn null_guards_return_invalid_argument() { + let rc = unsafe { kernel_cancel_token_new(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + let rc = unsafe { kernel_cancel_token_cancel(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + let mut fired = false; + let rc = unsafe { kernel_cancel_token_is_cancelled(std::ptr::null(), &mut fired) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + let rc = unsafe { kernel_cancel_token_free(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + } + + /// `token_ref` on a null handle yields `None` (used by the cancellable + /// entry points to treat a null token as "no cancellation"). + #[test] + fn token_ref_null_is_none() { + assert!(unsafe { token_ref(std::ptr::null()) }.is_none()); + } +} diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index bdb54a4c..470ba0c6 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -45,6 +45,7 @@ // module-wide allow that masked them in the skeleton phase is gone now // that bodies have landed. +pub mod cancel; pub mod error; pub mod metadata; pub mod result; @@ -158,6 +159,101 @@ where } } +/// Like [`block_on_ffi`], but races the future against a cooperative +/// [`CancellationToken`] so a host watcher thread can interrupt an otherwise +/// uninterruptible blocking C-ABI call (connect, or a hung result-stream +/// fetch). +/// +/// When `token` fires before the future completes, this **drops the future** +/// and returns [`KernelStatusCode::Cancelled`] with a typed `Cancelled` error +/// in the thread-local buffer. Dropping the future is what makes the cancel +/// *real* rather than a bare stop-waiting: the kernel's HTTP client is +/// `reqwest`, whose in-flight request futures abort when dropped (the crate's +/// documented cancellation model — see the CloudFetch streaming provider's own +/// token use), so the underlying socket work is torn down, not leaked. +/// +/// A **null** token means "no cancellation" and this behaves exactly like +/// [`block_on_ffi`] — so a single implementation body can back both the plain +/// and the `*_cancellable` entry points. An **already-fired** token short- +/// circuits to `Cancelled` without starting the future (matching a caller whose +/// deadline had already elapsed at the call site). +/// +/// The same threading contract as [`block_on_ffi`] applies (must be driven +/// from a non-runtime thread); reentrancy is rejected identically. +/// +/// [`CancellationToken`]: tokio_util::sync::CancellationToken +pub(crate) fn block_on_ffi_cancellable( + token: Option<&tokio_util::sync::CancellationToken>, + fut_builder: F, +) -> Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + // No token → identical to the plain path (one body, two entry shapes). + let Some(token) = token else { + return block_on_ffi(fut_builder); + }; + + error::clear_error(); + // Reject reentrancy explicitly (same reasoning as block_on_ffi): block_on + // from within any Tokio runtime would panic. + if tokio::runtime::Handle::try_current().is_ok() { + let e = crate::kernel_error::Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel C ABI called from within a Tokio runtime thread; entry points must be \ + invoked from a native (non-async-runtime) thread", + ); + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } + let rt = match runtime() { + Ok(rt) => rt, + Err(e) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + return Err(code); + } + }; + + // Race the work against the token. `select!` drops the losing branch's + // future, so a cancel here drops the in-flight request future. Wrapped in + // catch_unwind on the same AssertUnwindSafe basis as block_on_ffi so a + // panic inside the future can't unwind across `extern "C"`. + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + rt.block_on(async { + tokio::select! { + // Bias toward the cancel branch so an already-fired token is + // honoured deterministically before the work is polled — the + // "ctx already done at call time" case must not run the future. + biased; + _ = token.cancelled() => None, + out = fut_builder() => Some(out), + } + }) + })); + match result { + Ok(Some(Ok(value))) => Ok(value), + Ok(Some(Err(e))) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + Err(code) + } + Ok(None) => { + // Cancelled: the future was dropped mid-flight. Surface a typed + // Cancelled error so the host sees the same shape as a server-side + // Cancelled, and can prefer its own deadline/context error. + let e = crate::kernel_error::Error::cancelled() + .message("kernel C-ABI call cancelled by the caller's cancel token"); + let code = KernelStatusCode::from(e.code); + error::store_error(e); + Err(code) + } + Err(panic) => Err(handle_panic(panic)), + } +} + /// Run a **synchronous** fallible closure at an `extern "C"` boundary, /// catching any panic so it can't unwind across the FFI frame (UB) and /// mapping it to [`KernelStatusCode::Internal`]. diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index eec29de0..2cb9e8f2 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -38,6 +38,7 @@ #![allow(non_camel_case_types)] +use super::cancel::{kernel_cancel_token_t, token_ref}; use super::error::{store_and_code, store_invalid_arg}; use super::{catch_ffi, KernelStatusCode}; use crate::kernel_error::{Error, ErrorCode}; @@ -46,6 +47,7 @@ use crate::statement::executed::ExecutedStatement; use crate::statement::validity::ValidityFlag; use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow_array::{Array, RecordBatch}; +use tokio_util::sync::CancellationToken; /// Opaque result-stream handle. Boxed [`ResultStreamInner`]. #[repr(C)] @@ -196,6 +198,49 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( stream: *mut kernel_result_stream_t, out_array: *mut FFI_ArrowArray, out_schema: *mut FFI_ArrowSchema, +) -> KernelStatusCode { + next_batch_inner(stream, out_array, out_schema, None) +} + +/// Fetch the next batch, racing the (blocking) fetch against `cancel_token` so +/// a host can interrupt a hung CloudFetch chunk (a wedged S3 / pre-signed-URL +/// GET) instead of blocking on it forever. A **null** `cancel_token` behaves +/// exactly like [`kernel_result_stream_next_batch`]. +/// +/// If the token fires before the batch is ready, the fetch future is dropped +/// (aborting the in-flight download) and this returns +/// [`KernelStatusCode::Cancelled`]. The stream handle stays valid and owned by +/// the caller — close it with [`kernel_result_stream_close`] as usual; a +/// cancelled fetch does not consume or free it. +/// +/// # Safety +/// `stream`, `out_array`, `out_schema` carry the same contract as +/// [`kernel_result_stream_next_batch`]. `cancel_token`, if non-null, must be a +/// live handle from +/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) +/// not freed until this call returns; it is safe to fire from another thread +/// while this call is in flight. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_next_batch_cancellable( + stream: *mut kernel_result_stream_t, + out_array: *mut FFI_ArrowArray, + out_schema: *mut FFI_ArrowSchema, + cancel_token: *const kernel_cancel_token_t, +) -> KernelStatusCode { + next_batch_inner(stream, out_array, out_schema, token_ref(cancel_token)) +} + +/// Shared body for the two next-batch entry points. `token` (None for the plain +/// one) is raced against the fetch via `block_on_ffi_cancellable`. +/// +/// # Safety +/// See [`kernel_result_stream_next_batch`]. `token` must outlive the call when +/// `Some`. +unsafe fn next_batch_inner( + stream: *mut kernel_result_stream_t, + out_array: *mut FFI_ArrowArray, + out_schema: *mut FFI_ArrowSchema, + token: Option<&CancellationToken>, ) -> KernelStatusCode { catch_ffi(|| { let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { @@ -211,11 +256,12 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( let next: Option> = match inner { // Owned (metadata): drive the owned ResultStream lazily on the // runtime, one batch at a time, so an unbounded result streams - // with bounded memory. Running through block_on_ffi keeps the - // (possibly CloudFetch-backed) reader on the tokio reactor - // rather than off a plain C thread. + // with bounded memory. Running through block_on_ffi_cancellable + // keeps the (possibly CloudFetch-backed) reader on the tokio + // reactor rather than off a plain C thread, and lets a fired token + // drop the fetch future. ResultStreamInner::Owned { stream, .. } => { - match super::block_on_ffi(move || { + match super::block_on_ffi_cancellable(token, move || { let stream: &mut crate::result_stream::ResultStream = stream; Box::pin(async move { #[allow( @@ -248,8 +294,9 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // RecordBatch for FFI export. Explicit match on the // #[non_exhaustive] ResultBatch so a future non-Arrow // variant surfaces as a defined error, not a compile break - // with no fallback. - match super::block_on_ffi(move || { + // with no fallback. Cancellable so a hung CloudFetch chunk on + // the query path can be interrupted. + match super::block_on_ffi_cancellable(token, move || { let exec: &mut ExecutedStatement = exec; Box::pin(async move { #[allow( diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 24a18ef1..66a0966f 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -22,12 +22,14 @@ //! Transaction methods (autocommit / commit / rollback) are deferred to //! v0.1 per `docs/spec-v0.md` addendum A5. -use super::{block_on_ffi, KernelStatusCode}; +use super::cancel::{kernel_cancel_token_t, token_ref}; +use super::{block_on_ffi_cancellable, KernelStatusCode}; use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; use std::ffi::{c_char, CStr}; +use tokio_util::sync::CancellationToken; /// Opaque session handle. Boxed [`Session`] on the Rust side. #[repr(C)] @@ -533,6 +535,48 @@ unsafe fn set_on_config( pub unsafe extern "C" fn kernel_session_open( config: *mut KernelSessionConfig, out: *mut *mut kernel_session_t, +) -> KernelStatusCode { + session_open_inner(config, out, None) +} + +/// Open a session, racing the (blocking) connect against `cancel_token` so a +/// host can bound a slow warehouse cold-start / connect-time network partition +/// by its own deadline. A **null** `cancel_token` behaves exactly like +/// [`kernel_session_open`]. If the token fires (or is already fired) before +/// connect completes, the connect future is dropped — aborting the in-flight +/// request — and this returns [`KernelStatusCode::Cancelled`]; the config is +/// still consumed either way. +/// +/// The `cancel_token` is borrowed, not consumed: the caller still owns it and +/// must [`kernel_cancel_token_free`](crate::c_abi::cancel::kernel_cancel_token_free) +/// it after this returns. It is safe to fire the token from another thread +/// while this call is in flight (that is the intended use). +/// +/// # Safety +/// `config` and `out` carry the same contract as [`kernel_session_open`]. +/// `cancel_token`, if non-null, must be a live handle from +/// [`kernel_cancel_token_new`](crate::c_abi::cancel::kernel_cancel_token_new) +/// that is not freed until this call returns. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_open_cancellable( + config: *mut KernelSessionConfig, + out: *mut *mut kernel_session_t, + cancel_token: *const kernel_cancel_token_t, +) -> KernelStatusCode { + session_open_inner(config, out, token_ref(cancel_token)) +} + +/// Shared body for [`kernel_session_open`] and +/// [`kernel_session_open_cancellable`]. Owns the "config is consumed on every +/// path" contract in one place; `token` (None for the plain entry point) is +/// threaded into `build_session`'s `block_on`. +/// +/// # Safety +/// See [`kernel_session_open`]. `token` must outlive the call when `Some`. +unsafe fn session_open_inner( + config: *mut KernelSessionConfig, + out: *mut *mut kernel_session_t, + token: Option<&CancellationToken>, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); // The contract is "config is consumed on every path". Reclaim the box @@ -554,7 +598,7 @@ pub unsafe extern "C" fn kernel_session_open( } let config = config.expect("config is Some (checked above)"); - let session = match build_session(*config) { + let session = match build_session(*config, token) { Ok(s) => s, Err(code) => return code, // error already stored by build_session }; @@ -580,10 +624,15 @@ fn parse_scopes(s: &str) -> Option> { } /// Translate the C-side config into a [`Session`], driving the async -/// `Session::open` on the process-wide runtime. Errors are stored in the -/// thread-local buffer; the returned `KernelStatusCode` is the mapped -/// code. -fn build_session(config: KernelSessionConfig) -> Result { +/// `Session::open` on the process-wide runtime. When `token` is `Some`, the +/// connect is raced against it so a fired token drops the connect future +/// (aborting the in-flight request) and yields `Cancelled` — the connect-side +/// deadline path. Errors are stored in the thread-local buffer; the returned +/// `KernelStatusCode` is the mapped code. +fn build_session( + config: KernelSessionConfig, + token: Option<&CancellationToken>, +) -> Result { let KernelSessionConfig { connection, auth, @@ -593,7 +642,7 @@ fn build_session(config: KernelSessionConfig) -> Result (CString, CString, CString) { + let host = CString::new(uri).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + (host, http_path, token) +} + +/// A token that is ALREADY fired before the call short-circuits connect to +/// `Cancelled` without opening a session — the "ctx already done at call time" +/// case. The `biased` select in `block_on_ffi_cancellable` makes this +/// deterministic (the cancel branch is polled first). +#[test] +fn open_cancellable_prefired_token_short_circuits() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + // A create-session mock that, if ever hit, would succeed — so a failure + // to short-circuit surfaces as a Success (test fails on the assert). + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-prefired","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + // Fire BEFORE the call. + assert_eq!(kernel_cancel_token_cancel(tok), KernelStatusCode::Success); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + let rc = kernel_session_open_cancellable(config, &mut session, tok); + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a pre-fired token must short-circuit connect to Cancelled" + ); + assert!(session.is_null(), "no session handle on a cancelled open"); + + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + } +} + +/// A token fired from another thread DURING a stalled connect interrupts it: +/// the call returns `Cancelled` well before the (long) server delay elapses. +/// This is the connect-side deadline property — a slow warehouse cold-start no +/// longer blocks past the caller's deadline. +#[test] +fn open_cancellable_fires_during_stalled_connect() { + let rt = tokio::runtime::Runtime::new().unwrap(); + // Create-session stalls for 10s; the test fires cancel after ~150ms and + // must return long before the 10s would elapse. + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(10)) + .set_body_string(r#"{"session_id":"sess-stall","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + + // Watcher thread: fire the token after a short beat. `usize` shuttle so + // the raw pointer crosses the thread boundary (kernel_cancel_token_t is + // Send-safe to fire from another thread by contract). + let tok_addr = tok as usize; + let watcher = thread::spawn(move || { + thread::sleep(Duration::from_millis(150)); + let t = tok_addr as *mut kernel_cancel_token_t; + assert_eq!(kernel_cancel_token_cancel(t), KernelStatusCode::Success); + }); + + let start = Instant::now(); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + let rc = kernel_session_open_cancellable(config, &mut session, tok); + let elapsed = start.elapsed(); + + watcher.join().unwrap(); + + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a token fired mid-connect must interrupt the blocking connect" + ); + assert!(session.is_null(), "no session handle on a cancelled open"); + assert!( + elapsed < Duration::from_secs(5), + "cancel must abort the stalled connect promptly, took {elapsed:?}" + ); + + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + } +} + +/// A NULL token means "no cancellation": a normal (fast) create-session with a +/// NULL token completes normally. This pins that the cancellable entry point is +/// a strict superset of the plain one (the default path is unchanged). +#[test] +fn open_cancellable_null_token_behaves_like_plain_open() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-null-tok","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-null-tok")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + // NULL token → same as kernel_session_open. + let rc = kernel_session_open_cancellable(config, &mut session, std::ptr::null()); + assert_eq!(rc, KernelStatusCode::Success); + assert!(!session.is_null()); + + // Tidy up the opened session (fire-and-forget close). + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + +// ── mid-fetch cancel (kernel_result_stream_next_batch_cancellable) ──────────── + +/// A SUCCEEDED statement response carrying one inline-Arrow chunk of BIGINT rows, +/// so a real result stream can be opened and fetched over the C ABI. +fn succeeded_inline_body(statement_id: &str) -> String { + let batch = RecordBatch::try_from_iter([( + "n", + std::sync::Arc::new(Int64Array::from(vec![1_i64, 2, 3])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut w = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + w.write(&batch).unwrap(); + w.finish().unwrap(); + } + let attachment = STANDARD.encode(&ipc); + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { "column_count": 1, "columns": [ + { "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 } + ]}, + "total_chunk_count": 1, + "total_row_count": 3, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 3, + "byte_count": ipc.len() as i64, + "attachment": attachment, + }, + }) + .to_string() +} + +/// Drive the fetch path directly: open a session, execute a query that returns +/// an inline-Arrow result, obtain the result stream, then call +/// `kernel_result_stream_next_batch_cancellable`. A **pre-fired** token must +/// short-circuit the fetch to `Cancelled` (the biased select honors the token +/// before polling the fetch — the Gap 6 mid-fetch property), while a **NULL** +/// token on a fresh stream yields the batch normally (parity with the plain +/// next_batch). This exercises the actual `next_batch_cancellable` entry point, +/// not just the shared machinery the connect tests cover. +#[test] +fn next_batch_cancellable_prefired_token_short_circuits_fetch() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-fetch","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-fetch")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_inline_body("stmt-fetch")), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + // Open a session. + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let _held = address_config(config, &uri); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + + // execute a query → executed handle → result stream. + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT n FROM t").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_executed_statement_get_result_stream(exec, &mut stream), + KernelStatusCode::Success + ); + assert!(!stream.is_null()); + + // Pre-fire a token, then fetch: the biased select must honor the fired + // token and return Cancelled without producing a batch. + let mut tok: *mut kernel_cancel_token_t = std::ptr::null_mut(); + assert_eq!(kernel_cancel_token_new(&mut tok), KernelStatusCode::Success); + assert_eq!(kernel_cancel_token_cancel(tok), KernelStatusCode::Success); + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_next_batch_cancellable(stream, &mut arr, &mut sch, tok); + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "a pre-fired token must short-circuit the fetch to Cancelled" + ); + assert_eq!(kernel_cancel_token_free(tok), KernelStatusCode::Success); + + // A NULL token on the same stream fetches the batch normally (parity with + // the plain next_batch): the inline chunk yields a non-released array. + let mut arr2 = FFI_ArrowArray::empty(); + let mut sch2 = FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_next_batch_cancellable( + stream, + &mut arr2, + &mut sch2, + std::ptr::null(), + ); + assert_eq!( + rc, + KernelStatusCode::Success, + "NULL token must fetch normally" + ); + + // Teardown in the documented order: stream → executed → session. + kernel_result_stream_close(stream); + kernel_executed_statement_close(exec); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +}