From 66baec24b66f4f8a16a7f18141be075f9d8e2cac Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 3 Sep 2026 07:56:59 +0000 Subject: [PATCH 1/4] feat(c-abi): result-stream canceller to interrupt an in-flight next_batch (odbc#355-B) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit kernel_result_stream_next_batch blocks the calling C thread on a batch fetch that, for a CloudFetch-linked result, can take as long as the underlying request's own timeout. A host driver fetching on a background thread (the ODBC prefetch thread) then had no way to interrupt it, so SQLCancel / SQLCloseCursor / statement or connection teardown could wait for that request rather than returning promptly (databricks-odbc#355-B). Add a detached result-stream canceller mirroring the statement canceller's clonable-Arc ownership, but backed by a client-side tokio-util CancellationToken instead of a server RPC: * kernel_result_stream_canceller_new clones the stream's token into a detached handle. It borrows none of the stream's mutable state and issues no RPC, so — unlike the statement canceller — it is safe to obtain WHILE a next_batch is in flight and to fire concurrently with next_batch/close on the owning thread. * kernel_result_stream_canceller_cancel flips the token (non-blocking, idempotent). next_batch drives each fetch inside a tokio::select! (biased toward the fetch) against the token, so a cancel fired mid-fetch unwinds it and next_batch returns KernelStatusCode_Cancelled promptly. * Once fired the stream is permanently aborted: every later next_batch returns Cancelled rather than re-driving a reader left at an indeterminate position (the fetch future was dropped mid-await). * kernel_result_stream_canceller_free drops the box (no RPC); its order relative to kernel_result_stream_close is unconstrained. Tests: a crate-internal unit test parks next_batch inside a blocking reader and interrupts it from another thread (the headline in-flight case), plus pre-fire, permanence, outlives-close, and null-guard cases; an integration test proves the exported symbols work over a real session + wiremock transport. Header updated to match. Part C (bounded connection-close teardown) needs no kernel ABI: an abandoned execute's statement handle holds its own Arc, so the ODBC reaper can detach it and close the session without a use-after-free; that bound lives on the ODBC side. Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 43 ++ src/c_abi/result.rs | 429 ++++++++++++++++-- src/reader/test_utils.rs | 35 ++ ..._c_abi_result_stream_canceller_wiremock.rs | 155 +++++++ 4 files changed, 624 insertions(+), 38 deletions(-) create mode 100644 tests/v0_c_abi_result_stream_canceller_wiremock.rs diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 0eccb5b1..755844d6 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -212,6 +212,16 @@ 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; +/* Detached canceller for a result stream, returned by + * kernel_result_stream_canceller_new. Firing it interrupts an in-flight + * kernel_result_stream_next_batch so it returns KernelStatusCode_Cancelled + * promptly instead of blocking until the (possibly slow / CloudFetch-link) + * batch fetch finishes. Unlike the statement canceller it holds ONLY a shared + * client-side cancellation token (no server RPC, no borrow of the stream's + * mutable state), so — see its doc — it is safe to obtain and to fire + * concurrently with a next_batch/close on the owning thread. Once fired, the + * stream is permanently aborted (every later next_batch returns Cancelled). */ +typedef struct kernel_result_stream_canceller_t kernel_result_stream_canceller_t; /* ─── Session config ────────────────────────────────────────────────── * @@ -825,6 +835,39 @@ KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowSchema* out_schema); KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream); +/* ─── Result-stream cancellation (detached canceller) ───────────────── + * + * Interrupt an in-flight `kernel_result_stream_next_batch` (odbc#355-B). A + * host that fetches on a background thread and wants a bounded teardown + * (SQLCancel / SQLCloseCursor / statement or connection close) fires this to + * make a parked `next_batch` return promptly instead of waiting for the + * batch's own (possibly slow, CloudFetch-link) request to finish. + * + * `kernel_result_stream_canceller_new` clones the stream's cancellation token + * into a detached handle. Unlike the statement canceller, this borrows none of + * the stream's mutable state and issues no server RPC, so it may be obtained + * WHILE a `next_batch` is already in flight on another thread, and + * `kernel_result_stream_canceller_cancel` may be called concurrently with a + * `next_batch`/`kernel_result_stream_close` on the owning thread. `_cancel` is + * non-blocking and idempotent; it returns Success once the signal is delivered + * (it is the interrupted `next_batch` that returns + * `KernelStatusCode_Cancelled`). After a cancel the stream is permanently + * aborted: every later `next_batch` returns `Cancelled`, so the host must not + * expect to resume it — close it. + * + * The canceller shares the token's lifetime independently of the stream, so + * its free order is unconstrained: firing it after `kernel_result_stream_close` + * is a harmless no-op. Free it with `kernel_result_stream_canceller_free` + * (drives no RPC — drops the box). Do not free it while another thread is + * inside `_cancel` on the same handle. + */ +KernelStatusCode kernel_result_stream_canceller_new(kernel_result_stream_t* stream, + kernel_result_stream_canceller_t** out); +KernelStatusCode kernel_result_stream_canceller_cancel( + kernel_result_stream_canceller_t* canceller); +KernelStatusCode kernel_result_stream_canceller_free( + kernel_result_stream_canceller_t* canceller); + /* ─── Metadata ──────────────────────────────────────────────────────── * * Each returns a self-contained result stream (released via diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index eec29de0..cffd7b0a 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -39,13 +39,14 @@ #![allow(non_camel_case_types)] use super::error::{store_and_code, store_invalid_arg}; -use super::{catch_ffi, KernelStatusCode}; +use super::{block_on_ffi, catch_ffi, KernelStatusCode}; use crate::kernel_error::{Error, ErrorCode}; use crate::result_stream::{ResultBatch, SchemaRef}; 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)] @@ -53,8 +54,37 @@ pub struct kernel_result_stream_t { _private: [u8; 0], } -/// Backing state for a result-stream handle. -enum ResultStreamInner { +/// Opaque result-stream canceller handle. Boxed [`ResultStreamCanceller`]. +#[repr(C)] +pub struct kernel_result_stream_canceller_t { + _private: [u8; 0], +} + +/// Backing state for a result-stream handle: a shared cancellation token plus +/// the stream's backing shape. +/// +/// The `cancel` token is the interrupt hook (odbc#355-B). `next_batch` drives +/// the batch fetch inside a `tokio::select!` against `cancel.cancelled()`, so a +/// consumer that fired the token from another thread — via a +/// [`kernel_result_stream_canceller_t`] cloned from it — makes an in-flight +/// `next_batch` return promptly with [`KernelStatusCode::Cancelled`] instead of +/// blocking until the (possibly slow / CloudFetch-link) fetch finishes on its +/// own. The token is a purely client-side signal (no server RPC), is `Sync`, +/// and touches none of the stream's `&mut` state, so a cancel racing a +/// `next_batch`/`close` on the owning thread is well-defined: it only flips an +/// atomic the fetch's `select!` observes. +struct ResultStreamInner { + /// Fired by a cloned [`ResultStreamCanceller`] to interrupt an in-flight + /// `next_batch`. Once fired the stream is permanently aborted: `next_batch` + /// returns `Cancelled` on every subsequent call rather than re-driving a + /// partially-consumed reader (the fetch future was dropped mid-await, so + /// the reader's position is indeterminate). + cancel: CancellationToken, + shape: ResultStreamShape, +} + +/// The backing shape of a result stream (independent of cancellation). +enum ResultStreamShape { /// Self-contained owned stream (metadata path). The handle owns the /// `ResultStream` and drives `next_batch` lazily on the runtime (via /// `block_on_ffi`) — one batch per C call — so an unbounded metadata @@ -75,6 +105,19 @@ enum ResultStreamInner { }, } +/// Detached canceller for a result stream. Holds a clone of the stream's +/// [`CancellationToken`], so firing it interrupts an in-flight `next_batch`. +/// +/// A `CancellationToken` clone shares the same underlying atomic state, so the +/// canceller keeps working after the stream handle is closed — closing the +/// stream drops the stream's own token clone but not this one — and firing it +/// then is a harmless no-op (no `next_batch` is in flight). It holds no +/// reference to the stream's `&mut` state, so it is safe to `cancel()` from any +/// thread concurrently with `next_batch`/`close` on the owning thread. +struct ResultStreamCanceller { + cancel: CancellationToken, +} + /// Crate-internal: build an owned result-stream handle that lazily drives /// the given `ResultStream` (used by the metadata FFI). `schema` is /// captured up front so `get_schema` needs no runtime; each `next_batch` @@ -83,8 +126,10 @@ pub(crate) fn into_raw_result_stream( schema: SchemaRef, stream: crate::result_stream::ResultStream, ) -> *mut kernel_result_stream_t { - Box::into_raw(Box::new(ResultStreamInner::Owned { schema, stream })) - as *mut kernel_result_stream_t + Box::into_raw(Box::new(ResultStreamInner { + cancel: CancellationToken::new(), + shape: ResultStreamShape::Owned { schema, stream }, + })) as *mut kernel_result_stream_t } /// Crate-internal: build a result-stream handle that borrows from an @@ -98,8 +143,10 @@ pub(crate) unsafe fn into_raw_executed_stream( exec: *mut ExecutedStatement, valid: ValidityFlag, ) -> *mut kernel_result_stream_t { - Box::into_raw(Box::new(ResultStreamInner::Executed { exec, valid })) - as *mut kernel_result_stream_t + Box::into_raw(Box::new(ResultStreamInner { + cancel: CancellationToken::new(), + shape: ResultStreamShape::Executed { exec, valid }, + })) as *mut kernel_result_stream_t } /// Resolve the backing `ExecutedStatement` for the `Executed` shape. @@ -164,9 +211,9 @@ pub unsafe extern "C" fn kernel_result_stream_get_schema( if out.is_null() { return store_invalid_arg("kernel_result_stream_get_schema: out must not be null"); } - let schema = match inner { - ResultStreamInner::Owned { schema, .. } => schema.clone(), - ResultStreamInner::Executed { exec, valid } => match executed_ref(*exec, valid) { + let schema = match &mut inner.shape { + ResultStreamShape::Owned { schema, .. } => schema.clone(), + ResultStreamShape::Executed { exec, valid } => match executed_ref(*exec, valid) { Ok(e) => e.schema(), Err(code) => return code, }, @@ -207,28 +254,63 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( ); } - // Pull the next owned batch from whichever backing shape this is. - let next: Option> = match inner { + // Abort hook (odbc#355-B). If the stream's cancellation token was fired + // — either before this call or, below, DURING the fetch — the batch + // fetch is abandoned and this returns `Cancelled` promptly rather than + // blocking on a slow (CloudFetch-link) request. Once fired the token + // stays fired, so every subsequent `next_batch` also returns here: the + // fetch future was dropped mid-await, leaving the reader's position + // indeterminate, so re-driving it is not sound. A pre-check short-circuits + // the already-cancelled case without touching the runtime; the in-flight + // case is handled by the `select!` inside each fetch future below. + if inner.cancel.is_cancelled() { + return store_and_code( + Error::cancelled() + .message("result stream was cancelled") + .with_retryable(false), + ); + } + let cancel = inner.cancel.clone(); + + // Pull the next owned batch from whichever backing shape this is. Each + // fetch runs inside a `tokio::select!` against a clone of the stream's + // cancellation token, so a cancel fired from another thread while the + // fetch is in flight wins the race and unwinds the fetch (dropping its + // future at the await point) instead of waiting for it to complete. The + // token clone shares the same atomic state as the canceller's clone, so + // this observes a cancel fired at any instant. + let next: Option> = match &mut inner.shape { // 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. - ResultStreamInner::Owned { stream, .. } => { - match super::block_on_ffi(move || { + ResultStreamShape::Owned { stream, .. } => { + match block_on_ffi(move || { let stream: &mut crate::result_stream::ResultStream = stream; Box::pin(async move { - #[allow( - unreachable_patterns, - reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" - )] - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(Error::not_implemented().message( - "metadata stream yielded a non-Arrow batch; the C ABI exports \ - Arrow only", - )), - None => Ok(None), + tokio::select! { + // Bias the fetch: if both are ready, prefer the batch + // so a completed fetch is not discarded by a cancel + // that arrived at the same instant. + biased; + fetched = stream.next_batch() => { + #[allow( + unreachable_patterns, + reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" + )] + match fetched? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(Error::not_implemented().message( + "metadata stream yielded a non-Arrow batch; the C ABI \ + exports Arrow only", + )), + None => Ok(None), + } + } + _ = cancel.cancelled() => Err(Error::cancelled() + .message("result stream cancelled during next_batch") + .with_retryable(false)), } }) }) { @@ -237,7 +319,7 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( Err(code) => return code, // error already stored } } - ResultStreamInner::Executed { exec, valid } => { + ResultStreamShape::Executed { exec, valid } => { let exec = match executed_ref(*exec, valid) { Ok(e) => e, Err(code) => return code, @@ -249,20 +331,28 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // #[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 || { + match block_on_ffi(move || { let exec: &mut ExecutedStatement = exec; Box::pin(async move { - #[allow( - unreachable_patterns, - reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" - )] - match exec.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(Error::not_implemented().message( - "result stream yielded a non-Arrow batch; the C ABI exports \ - Arrow only", - )), - None => Ok(None), + tokio::select! { + biased; + fetched = exec.next_batch() => { + #[allow( + unreachable_patterns, + reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" + )] + match fetched? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(Error::not_implemented().message( + "result stream yielded a non-Arrow batch; the C ABI \ + exports Arrow only", + )), + None => Ok(None), + } + } + _ = cancel.cancelled() => Err(Error::cancelled() + .message("result stream cancelled during next_batch") + .with_retryable(false)), } }) }) { @@ -320,6 +410,102 @@ pub unsafe extern "C" fn kernel_result_stream_close( KernelStatusCode::Success } +// ─── Result-stream cancellation (detached canceller) ───────────────────────── + +/// Create a detached canceller for `stream` (odbc#355-B). Obtain it while the +/// stream is live; from another thread, `kernel_result_stream_canceller_cancel` +/// then interrupts an in-flight `kernel_result_stream_next_batch`, which returns +/// `KernelStatusCode::Cancelled` promptly instead of blocking until the fetch +/// completes on its own. +/// +/// The canceller holds only a clone of the stream's cancellation token (a shared +/// atomic flag), so — unlike the statement canceller — it borrows none of the +/// stream's `&mut` state and issues no server RPC. It is therefore safe to obtain +/// while a `next_batch` is already in flight, and safe to `cancel()`/`free()` in +/// any order relative to `kernel_result_stream_close`: firing it after the stream +/// is closed is a harmless no-op (the shared token outlives the stream's own +/// clone). Free it with `kernel_result_stream_canceller_free`; the free drives no +/// RPC and only drops the box. +/// +/// # Safety +/// `stream` must be a live result-stream handle from a `kernel_*` call that +/// produces one; `out` must be a valid, writable pointer. Unlike the statement +/// canceller, a `next_batch` MAY be in flight on another thread when this is +/// called — it reads only the shared token, not the stream's mutable state. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_canceller_new( + stream: *mut kernel_result_stream_t, + out: *mut *mut kernel_result_stream_canceller_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(inner) = (stream as *mut ResultStreamInner).as_ref() else { + return store_invalid_arg("kernel_result_stream_canceller_new: stream must not be null"); + }; + if out.is_null() { + return store_invalid_arg("kernel_result_stream_canceller_new: out must not be null"); + } + let handle = ResultStreamCanceller { + cancel: inner.cancel.clone(), + }; + std::ptr::write( + out, + Box::into_raw(Box::new(handle)) as *mut kernel_result_stream_canceller_t, + ); + KernelStatusCode::Success +} + +/// Fire the cancellation of the result stream this canceller was created for +/// (odbc#355-B). Purely client-side (no server RPC): it flips the shared token, +/// which an in-flight `kernel_result_stream_next_batch` observes via its +/// `tokio::select!` and unwinds. Idempotent, non-blocking, and safe to call +/// concurrently with `next_batch`/`close` on the stream's owning thread. +/// +/// Always returns `Success` for a live handle. After this returns, the stream is +/// permanently aborted: every subsequent `next_batch` returns `Cancelled`. +/// +/// # Safety +/// `canceller` must be a live handle from `kernel_result_stream_canceller_new`. +/// Unlike the statement canceller, this does NOT block on an RPC, so it need not +/// be driven from an abandonable thread — but it must still not be freed by +/// another thread concurrently with this call. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_canceller_cancel( + canceller: *mut kernel_result_stream_canceller_t, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (canceller as *mut ResultStreamCanceller).as_ref() else { + return store_invalid_arg( + "kernel_result_stream_canceller_cancel: handle must not be null", + ); + }; + handle.cancel.cancel(); + KernelStatusCode::Success + }) +} + +/// Free a result-stream canceller handle. Does not touch the originating stream. +/// Drives no RPC (only drops the box), so its order relative to +/// `kernel_result_stream_close` is free. +/// +/// # Safety +/// `canceller` must have been returned by `kernel_result_stream_canceller_new` +/// and not previously freed. Must not be freed while another thread is inside +/// `kernel_result_stream_canceller_cancel` on this handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_canceller_free( + canceller: *mut kernel_result_stream_canceller_t, +) -> KernelStatusCode { + catch_ffi(|| { + if canceller.is_null() { + return store_invalid_arg( + "kernel_result_stream_canceller_free: handle must not be null", + ); + } + drop(Box::from_raw(canceller as *mut ResultStreamCanceller)); + KernelStatusCode::Success + }) +} + #[cfg(test)] mod tests { use super::*; @@ -396,4 +582,171 @@ mod tests { let rc = unsafe { kernel_result_stream_close(std::ptr::null_mut()) }; assert_eq!(rc, KernelStatusCode::InvalidArgument); } + + /// Canceller null guards (odbc#355-B). + #[test] + fn canceller_null_guards_return_invalid_argument() { + let mut out: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); + let rc = unsafe { kernel_result_stream_canceller_new(std::ptr::null_mut(), &mut out) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + + let rc = unsafe { kernel_result_stream_canceller_cancel(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + + let rc = unsafe { kernel_result_stream_canceller_free(std::ptr::null_mut()) }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + } + + /// Firing the canceller BEFORE `next_batch` makes it return `Cancelled` + /// without touching the reader — the pre-check path (odbc#355-B). + #[test] + fn cancel_before_next_batch_returns_cancelled() { + let (schema, batch) = one_row_batch(); + let stream = owned_stream_over(schema, vec![batch]); + + let mut canceller: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream, &mut canceller) }, + KernelStatusCode::Success + ); + // canceller_cancel itself returns Success (the SIGNAL was delivered); + // it is the next_batch that then reports Cancelled. + assert_eq!( + unsafe { kernel_result_stream_canceller_cancel(canceller) }, + KernelStatusCode::Success + ); + + // The very first next_batch after a cancel returns Cancelled, NOT the + // buffered batch — the stream is aborted. + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = unsafe { kernel_result_stream_next_batch(stream, &mut arr, &mut sch) }; + assert_eq!(rc, KernelStatusCode::Cancelled); + assert!( + arr.is_released(), + "no batch should be handed out after cancel" + ); + + // A second call still reports Cancelled (permanent abort), never hangs + // or re-drives the reader. + let rc2 = unsafe { kernel_result_stream_next_batch(stream, &mut arr, &mut sch) }; + assert_eq!(rc2, KernelStatusCode::Cancelled); + + unsafe { kernel_result_stream_canceller_free(canceller) }; + unsafe { kernel_result_stream_close(stream) }; + } + + /// The headline in-flight test (odbc#355-B): a `next_batch` blocked inside + /// the reader's fetch is interrupted by a cancel fired from ANOTHER thread, + /// and returns `Cancelled` promptly rather than waiting for the fetch (which + /// this test never releases). Without the `select!` against the token, the + /// consumer thread would block forever on the reader. + #[test] + fn cancel_interrupts_an_in_flight_next_batch() { + use crate::reader::test_utils::BlockingReader; + use crate::result_stream::ResultStream; + use std::sync::atomic::{AtomicI32, Ordering}; + + // Raw pointers are not Send; wrap for the deliberate cross-thread move + // (the C ABI is explicitly callable from any non-runtime thread). + struct SendPtr(*mut T); + unsafe impl Send for SendPtr {} + impl SendPtr { + fn get(self) -> *mut T { + self.0 + } + } + + let schema: SchemaRef = + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let reader = BlockingReader { + schema: schema.clone(), + entered: entered.clone(), + release: release.clone(), + }; + + // Build the owned stream over the blocking reader on a throwaway runtime + // (from_reader is async), then obtain a canceller before driving it. + let rt = tokio::runtime::Runtime::new().unwrap(); + let stream_ptr = { + let stream = + rt.block_on(async { ResultStream::from_reader(Box::new(reader)).await.unwrap() }); + into_raw_result_stream(schema, stream) + }; + let mut canceller: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream_ptr, &mut canceller) }, + KernelStatusCode::Success + ); + + // Drive next_batch on a worker thread; it parks inside the reader. + let stream_send = SendPtr(stream_ptr); + let rc_slot = Arc::new(AtomicI32::new(-1)); + let rc_slot_thread = rc_slot.clone(); + let fetch_thread = std::thread::spawn(move || { + let stream = stream_send.get(); + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = unsafe { kernel_result_stream_next_batch(stream, &mut arr, &mut sch) }; + rc_slot_thread.store(rc as i32, Ordering::SeqCst); + }); + + // Wait until the reader is definitely parked inside the fetch await, so + // the cancel lands on a genuinely in-flight next_batch (not before it). + rt.block_on(async { + tokio::time::timeout(std::time::Duration::from_secs(5), entered.notified()) + .await + .expect("reader did not enter next_batch within 5s"); + }); + + // Fire the cancel from this (different) thread; the parked next_batch + // must unwind. Bound the join so a regression (no interrupt) fails the + // test instead of hanging — the reader is never released. + assert_eq!( + unsafe { kernel_result_stream_canceller_cancel(canceller) }, + KernelStatusCode::Success + ); + fetch_thread + .join() + .expect("next_batch thread panicked or hung"); + assert_eq!( + rc_slot.load(Ordering::SeqCst), + KernelStatusCode::Cancelled as i32, + "an in-flight next_batch interrupted by cancel must return Cancelled" + ); + + unsafe { kernel_result_stream_canceller_free(canceller) }; + unsafe { kernel_result_stream_close(stream_ptr) }; + } + + /// The canceller outlives the stream: closing the stream first, then firing + /// and freeing the canceller, is a harmless no-op — the shared token clone + /// keeps working after the stream's own clone is dropped (odbc#355-B). + #[test] + fn canceller_outlives_stream_close() { + let (schema, batch) = one_row_batch(); + let stream = owned_stream_over(schema, vec![batch]); + + let mut canceller: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream, &mut canceller) }, + KernelStatusCode::Success + ); + + // Close the stream BEFORE cancelling/freeing the canceller. + unsafe { kernel_result_stream_close(stream) }; + + // Firing the (now orphaned) canceller is a safe no-op, and freeing it + // does not touch the freed stream. + assert_eq!( + unsafe { kernel_result_stream_canceller_cancel(canceller) }, + KernelStatusCode::Success + ); + assert_eq!( + unsafe { kernel_result_stream_canceller_free(canceller) }, + KernelStatusCode::Success + ); + } } diff --git a/src/reader/test_utils.rs b/src/reader/test_utils.rs index 0e4e3ffb..f4657b0a 100644 --- a/src/reader/test_utils.rs +++ b/src/reader/test_utils.rs @@ -20,6 +20,7 @@ use arrow_array::RecordBatch; use arrow_schema::{Schema, SchemaRef}; use async_trait::async_trait; use std::sync::Arc; +use tokio::sync::Notify; /// A simple mock reader that returns predefined batches. pub struct MockReader { @@ -100,6 +101,40 @@ impl ResultReader for BatchThenErrorReader { } } +/// A reader whose `next_batch()` blocks indefinitely until explicitly +/// released, and signals when it has actually entered the blocked await. Used +/// to prove that a result-stream cancellation interrupts an in-flight fetch +/// (odbc#355-B): a consumer starts `next_batch`, waits on `entered` until the +/// reader is definitely parked inside the await, then cancels — and the fetch +/// must unwind promptly rather than waiting on `release`, which the test never +/// fires. +/// +/// `entered` is notified once the reader parks; `release` is awaited to unblock +/// it. Both are `Arc` so the test thread holds its own clones. If a +/// cancellation drops the future while it is parked here, `release` is simply +/// never awaited to completion — no batch is produced. +pub struct BlockingReader { + pub schema: SchemaRef, + pub entered: Arc, + pub release: Arc, +} + +#[async_trait] +impl ResultReader for BlockingReader { + async fn schema(&self) -> Result { + Ok(self.schema.clone()) + } + + async fn next_batch(&mut self) -> Result> { + // Announce that the fetch is now parked, then block until released. + // A cancellation that drops this future while it is awaiting `release` + // is exactly the in-flight-interrupt path under test. + self.entered.notify_one(); + self.release.notified().await; + Ok(None) + } +} + /// A reader that returns an error on `schema()`. pub struct SchemaErrorReader; diff --git a/tests/v0_c_abi_result_stream_canceller_wiremock.rs b/tests/v0_c_abi_result_stream_canceller_wiremock.rs new file mode 100644 index 00000000..e05c99bb --- /dev/null +++ b/tests/v0_c_abi_result_stream_canceller_wiremock.rs @@ -0,0 +1,155 @@ +// 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. + +//! Wiremock test for the C ABI result-stream canceller +//! (`kernel_result_stream_canceller_new` / `_cancel` / `_free`, odbc#355-B). +//! +//! The deterministic in-flight interrupt (a `next_batch` parked inside a +//! blocking fetch, unwound by a cancel from another thread) is covered by the +//! crate-internal unit test `c_abi::result::tests:: +//! cancel_interrupts_an_in_flight_next_batch`, which uses a controllable +//! blocking reader. This integration test proves the **exported** canceller +//! symbols link and work against a real session + transport: open a session +//! over wiremock, take a live result stream, create a canceller from it, fire +//! it, and confirm the subsequent `next_batch` reports `Cancelled` and the +//! stream stays permanently aborted (never hangs, never re-drives the reader). +//! +//! Like the other C ABI wiremock tests, the entry points run on the kernel's +//! process-wide runtime inside `block_on_ffi`, so they must be called from a +//! plain (non-async) thread — hence `#[test]`, with a dedicated runtime only +//! to host the wiremock server. + +use std::ffi::CString; + +use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; +use databricks_sql_kernel::c_abi::metadata::kernel_metadata_list_table_types; +use databricks_sql_kernel::c_abi::result::{ + kernel_result_stream_canceller_cancel, kernel_result_stream_canceller_free, + kernel_result_stream_canceller_new, kernel_result_stream_canceller_t, + kernel_result_stream_close, kernel_result_stream_next_batch, kernel_result_stream_t, +}; +use databricks_sql_kernel::c_abi::session::{ + kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, + kernel_session_config_set_http_path, kernel_session_open, kernel_session_t, + KernelSessionConfig, +}; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +/// Open a real C ABI session against `uri` (PAT auth). Mirrors the session +/// setup shared by the other C ABI wiremock tests. +unsafe fn open_session(uri: &str) -> *mut kernel_session_t { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + 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()); + session +} + +/// Firing an exported result-stream canceller aborts the stream: the next +/// `next_batch` returns `Cancelled` and the stream stays aborted across +/// subsequent calls (never yields the buffered rows, never hangs). +#[test] +fn exported_canceller_aborts_the_stream() { + 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-rs-cancel","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-rs-cancel")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session(&uri); + + // A live owned result stream (list_table_types is static/no-wire, so + // it is a well-defined stream regardless of the mock's query surface). + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_metadata_list_table_types(session, &mut stream), + KernelStatusCode::Success + ); + assert!(!stream.is_null()); + + // Create a canceller from the live stream and fire it. + let mut canceller: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); + assert_eq!( + kernel_result_stream_canceller_new(stream, &mut canceller), + KernelStatusCode::Success + ); + assert!(!canceller.is_null()); + assert_eq!( + kernel_result_stream_canceller_cancel(canceller), + KernelStatusCode::Success + ); + + // next_batch after the cancel returns Cancelled with no batch, and a + // repeat call still reports Cancelled (permanent abort — never hangs). + for _ in 0..2 { + let mut arr = FFI_ArrowArray::empty(); + let mut sch = FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_next_batch(stream, &mut arr, &mut sch); + assert_eq!( + rc, + KernelStatusCode::Cancelled, + "next_batch after cancel must report Cancelled" + ); + assert!( + arr.is_released(), + "no batch may be handed out after a cancel" + ); + } + + assert_eq!( + kernel_result_stream_canceller_free(canceller), + KernelStatusCode::Success + ); + assert_eq!( + kernel_result_stream_close(stream), + KernelStatusCode::Success + ); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} From 9a068860049505b07c9f1ea1eae5985b9377f4a4 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 3 Sep 2026 08:25:06 +0000 Subject: [PATCH 2/4] fix(c-abi): project result-stream fields separately to keep canceller_new sound during next_batch (odbc#355 review F1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit kernel_result_stream_canceller_new and next_batch both formed a reference over the WHOLE ResultStreamInner (.as_ref() / .as_mut()). The API docs bless calling canceller_new while a next_batch is in flight on another thread — but a whole-struct &mut carries a noalias guarantee over the entire allocation, so a &ResultStreamInner (canceller_new) overlapping a live &mut ResultStreamInner (next_batch, held across the fetch) is UB at the reference level even though each side only touches a different field. Fix: split ResultStreamInner into its two fields at the access site via raw-pointer projection. next_batch and get_schema now take &mut only of (*p).shape (addr_of_mut!) and clone (*p).cancel through addr_of!; canceller_new reads only (*p).cancel through addr_of!. The fetch's live borrow therefore covers only `shape`, and a concurrent canceller_new's read covers only `cancel` (a Sync atomic) — disjoint fields, never an overlapping whole-struct reference, so the documented concurrent-obtain contract is now actually sound. The headline in-flight test now obtains the canceller AFTER the fetch thread has parked inside next_batch (rather than before spawning it), so it exercises the concurrent canceller_new-during-next_batch path the docs bless and the fix protects — run under miri / ThreadSanitizer to check the aliasing at the reference level. cargo test c_abi::result (6) + the canceller wiremock integration test pass; clippy + fmt clean. Signed-off-by: Vikrant Puppala --- src/c_abi/result.rs | 81 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 63 insertions(+), 18 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index cffd7b0a..e14fc5fd 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -205,13 +205,20 @@ pub unsafe extern "C" fn kernel_result_stream_get_schema( out: *mut FFI_ArrowSchema, ) -> KernelStatusCode { catch_ffi(|| { - let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { + if stream.is_null() { return store_invalid_arg("kernel_result_stream_get_schema: stream must not be null"); - }; + } if out.is_null() { return store_invalid_arg("kernel_result_stream_get_schema: out must not be null"); } - let schema = match &mut inner.shape { + // Project to `&mut (*p).shape` only, never a whole-struct `&mut` — so a + // concurrent `kernel_result_stream_canceller_new` (which reads only the + // disjoint `cancel` field) does not alias it (odbc#355 review F1). + // SAFETY: live box (non-null checked); `shape` has a single accessor per + // the no-concurrent-next_batch/get_schema contract. + let p = stream as *mut ResultStreamInner; + let shape: &mut ResultStreamShape = &mut *std::ptr::addr_of_mut!((*p).shape); + let schema = match shape { ResultStreamShape::Owned { schema, .. } => schema.clone(), ResultStreamShape::Executed { exec, valid } => match executed_ref(*exec, valid) { Ok(e) => e.schema(), @@ -245,15 +252,33 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( out_schema: *mut FFI_ArrowSchema, ) -> KernelStatusCode { catch_ffi(|| { - let Some(inner) = (stream as *mut ResultStreamInner).as_mut() else { + if stream.is_null() { return store_invalid_arg("kernel_result_stream_next_batch: stream must not be null"); - }; + } if out_array.is_null() || out_schema.is_null() { return store_invalid_arg( "kernel_result_stream_next_batch: out pointers must not be null", ); } + // Borrow the two fields SEPARATELY through raw-pointer projection rather + // than forming a single `&mut ResultStreamInner` over the whole struct + // (odbc#355 review F1). A whole-struct `&mut` carries a noalias guarantee + // over the ENTIRE allocation, so holding it across the fetch below would + // be UB the instant another thread calls `kernel_result_stream_canceller + // _new` — which reads `cancel` and which this API's docs explicitly bless + // calling while a `next_batch` is in flight. Projecting to `&mut (*p).shape` + // and `&(*p).cancel` yields references over DISJOINT fields: the fetch's + // live borrow covers only `shape`, and a concurrent `canceller_new`'s read + // covers only `cancel` (a `Sync` atomic), so they never alias. + let p = stream as *mut ResultStreamInner; + // SAFETY: `p` is a live result-stream box (non-null checked above); the + // caller's contract forbids a *second* next_batch/close on the same handle + // concurrently, so `shape` has a single mutable accessor. `cancel` is only + // read here (clone) and by a concurrent canceller — a disjoint, Sync field. + let cancel: CancellationToken = (*std::ptr::addr_of!((*p).cancel)).clone(); + let shape: &mut ResultStreamShape = &mut *std::ptr::addr_of_mut!((*p).shape); + // Abort hook (odbc#355-B). If the stream's cancellation token was fired // — either before this call or, below, DURING the fetch — the batch // fetch is abandoned and this returns `Cancelled` promptly rather than @@ -263,14 +288,13 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // indeterminate, so re-driving it is not sound. A pre-check short-circuits // the already-cancelled case without touching the runtime; the in-flight // case is handled by the `select!` inside each fetch future below. - if inner.cancel.is_cancelled() { + if cancel.is_cancelled() { return store_and_code( Error::cancelled() .message("result stream was cancelled") .with_retryable(false), ); } - let cancel = inner.cancel.clone(); // Pull the next owned batch from whichever backing shape this is. Each // fetch runs inside a `tokio::select!` against a clone of the stream's @@ -279,7 +303,7 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // future at the await point) instead of waiting for it to complete. The // token clone shares the same atomic state as the canceller's clone, so // this observes a cancel fired at any instant. - let next: Option> = match &mut inner.shape { + let next: Option> = match shape { // 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 @@ -431,21 +455,30 @@ pub unsafe extern "C" fn kernel_result_stream_close( /// `stream` must be a live result-stream handle from a `kernel_*` call that /// produces one; `out` must be a valid, writable pointer. Unlike the statement /// canceller, a `next_batch` MAY be in flight on another thread when this is -/// called — it reads only the shared token, not the stream's mutable state. +/// called — it reads ONLY the shared `cancel` token field, via raw-pointer +/// projection, and never forms a reference over the whole `ResultStreamInner`. +/// That is what keeps it sound against a concurrent `next_batch`, which borrows +/// only the disjoint `shape` field (a whole-struct `&`/`&mut` would alias even +/// though the fields touched differ — odbc#355 review F1). #[no_mangle] pub unsafe extern "C" fn kernel_result_stream_canceller_new( stream: *mut kernel_result_stream_t, out: *mut *mut kernel_result_stream_canceller_t, ) -> KernelStatusCode { crate::c_abi::error::clear_error(); - let Some(inner) = (stream as *mut ResultStreamInner).as_ref() else { + if stream.is_null() { return store_invalid_arg("kernel_result_stream_canceller_new: stream must not be null"); - }; + } if out.is_null() { return store_invalid_arg("kernel_result_stream_canceller_new: out must not be null"); } + // Read ONLY the `cancel` field through a raw-pointer projection — never a + // reference over the whole struct — so this is sound even while another + // thread holds `&mut (*p).shape` inside next_batch (disjoint fields; `cancel` + // is a `Sync` atomic). SAFETY: `stream` is a live box (non-null checked). + let p = stream as *mut ResultStreamInner; let handle = ResultStreamCanceller { - cancel: inner.cancel.clone(), + cancel: (*std::ptr::addr_of!((*p).cancel)).clone(), }; std::ptr::write( out, @@ -641,6 +674,13 @@ mod tests { /// and returns `Cancelled` promptly rather than waiting for the fetch (which /// this test never releases). Without the `select!` against the token, the /// consumer thread would block forever on the reader. + /// + /// This also exercises the blessed CONCURRENT path (odbc#355 review F1): the + /// canceller is obtained via `kernel_result_stream_canceller_new` AFTER the + /// fetch thread has parked inside `next_batch`, i.e. while a `next_batch` is + /// in flight — the exact race the field-projection soundness fix protects. + /// Run under `cargo +nightly miri test` / ThreadSanitizer to check the + /// aliasing at the reference level, not just the observable outcome. #[test] fn cancel_interrupts_an_in_flight_next_batch() { use crate::reader::test_utils::BlockingReader; @@ -668,18 +708,13 @@ mod tests { }; // Build the owned stream over the blocking reader on a throwaway runtime - // (from_reader is async), then obtain a canceller before driving it. + // (from_reader is async). let rt = tokio::runtime::Runtime::new().unwrap(); let stream_ptr = { let stream = rt.block_on(async { ResultStream::from_reader(Box::new(reader)).await.unwrap() }); into_raw_result_stream(schema, stream) }; - let mut canceller: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); - assert_eq!( - unsafe { kernel_result_stream_canceller_new(stream_ptr, &mut canceller) }, - KernelStatusCode::Success - ); // Drive next_batch on a worker thread; it parks inside the reader. let stream_send = SendPtr(stream_ptr); @@ -701,6 +736,16 @@ mod tests { .expect("reader did not enter next_batch within 5s"); }); + // Obtain the canceller NOW — while next_batch is in flight on the other + // thread. This is the concurrent-`canceller_new`-during-`next_batch` path + // the docs bless; it must be sound (disjoint field projection) and must + // succeed here. + let mut canceller: *mut kernel_result_stream_canceller_t = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream_ptr, &mut canceller) }, + KernelStatusCode::Success + ); + // Fire the cancel from this (different) thread; the parked next_batch // must unwind. Bound the join so a regression (no interrupt) fails the // test instead of hanging — the reader is never released. From 7d0f2c4cf9f25a0b15f934f7bf73b2f361350482 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 3 Sep 2026 09:50:19 +0000 Subject: [PATCH 3/4] refactor(c-abi): share the cancel select! across both result-stream shapes; clarify client-side scope (odbc#355 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review follow-ups on #312: - F1 (Executed-arm cancel logic untested): the Owned and Executed shapes had duplicated tokio::select! + Arrow-variant-mapping blocks, so the reviewer correctly noted the Executed arm's cancellation path was never exercised (all tests build Owned streams). Extract one shared async wrapper, select_next_batch, that both arms route their next_batch future through — generic over Borrow so it takes the owned arm's Option and the executed arm's Option<&ResultBatch> alike. The cancellation/select logic is now a SINGLE code path, so the mid-fetch-cancel unit test covers the exact select! the Executed arm uses; the arms differ only in how they produce the batch future and the Executed arm's executed_ref stale-handle guard. - F2 (client-side scope): document on ResultStreamInner that firing the token bounds the CALLER'S wait (drops the next_batch future) but does NOT abort the underlying CloudFetch download — the provider's spawned download task keeps a worker + connection busy until it finishes/times out. A host wanting bounded teardown gets a bounded caller-return, not immediate reclamation; close the stream to release the download on its own completion. cargo test c_abi::result (6) + clippy + fmt clean. Signed-off-by: Vikrant Puppala --- src/c_abi/result.rs | 148 ++++++++++++++++++++++++++------------------ 1 file changed, 87 insertions(+), 61 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index e14fc5fd..461e05d3 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -73,6 +73,18 @@ pub struct kernel_result_stream_canceller_t { /// and touches none of the stream's `&mut` state, so a cancel racing a /// `next_batch`/`close` on the owning thread is well-defined: it only flips an /// atomic the fetch's `select!` observes. +/// +/// SCOPE (odbc#355 review): firing this token bounds the CALLER'S wait — the +/// `next_batch` future is dropped at its await point and the C call returns +/// promptly — but it does NOT abort the underlying request. For a CloudFetch +/// download the provider runs the fetch on a spawned task and awaits its +/// `JoinHandle`; dropping the `next_batch` future drops that await, not the +/// detached download, which keeps a runtime worker + connection busy until it +/// finishes or hits its own timeout. This token is intentionally not wired into +/// the provider's own `cancel_token`. A host using this for bounded TEARDOWN +/// gets a bounded caller-return, not immediate reclamation of the in-flight +/// download — close the stream (and, for a sync-executed statement, the executed +/// handle) to release those on their own completion. struct ResultStreamInner { /// Fired by a cloned [`ResultStreamCanceller`] to interrupt an in-flight /// `next_batch`. Once fired the stream is permanently aborted: `next_batch` @@ -190,6 +202,55 @@ unsafe fn executed_ref<'a>( Ok(e) } +/// Shared cancellation wrapper for a single batch fetch (odbc#355-B, review F1). +/// +/// Runs `fetch` (the backing shape's `next_batch` future — the owned +/// `ResultStream`'s or the executed handle's) inside a `tokio::select!` against +/// `cancel.cancelled()`, and maps the fetched batch to an owned `RecordBatch` +/// for FFI export. BOTH C ABI stream shapes route their fetch through this one +/// function, so the cancellation/select logic is a single code path (rather than +/// duplicated per arm): the Owned unit test that fires a cancel mid-fetch +/// therefore exercises the exact `select!` the Executed arm uses too. +/// +/// `fetch` yields `Result>` where `B` borrows a `ResultBatch` — the +/// owned arm's `next_batch` yields `Option` (B = ResultBatch), the +/// executed arm's yields `Option<&ResultBatch>` (B = &ResultBatch); both are +/// `.borrow()`ed and cloned here. `kind` names the shape for the non-Arrow error. +/// +/// `biased` prefers the fetch: if a batch and a cancel are both ready, the +/// completed batch is returned rather than discarded by a same-instant cancel. +async fn select_next_batch( + fetch: Fut, + cancel: CancellationToken, + kind: &str, +) -> crate::kernel_error::Result> +where + B: std::borrow::Borrow, + Fut: std::future::Future>>, +{ + tokio::select! { + biased; + fetched = fetch => { + #[allow( + unreachable_patterns, + reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" + )] + match fetched? { + Some(b) => match b.borrow() { + ResultBatch::Arrow(rb) => Ok(Some(rb.clone())), + _ => Err(Error::not_implemented().message( + format!("{kind} yielded a non-Arrow batch; the C ABI exports Arrow only"), + )), + }, + None => Ok(None), + } + } + _ = cancel.cancelled() => Err(Error::cancelled() + .message("result stream cancelled during next_batch") + .with_retryable(false)), + } +} + /// Export the schema as an `FFI_ArrowSchema`. /// /// On success, `*out` holds an `FFI_ArrowSchema` the caller releases via @@ -296,13 +357,19 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( ); } - // Pull the next owned batch from whichever backing shape this is. Each - // fetch runs inside a `tokio::select!` against a clone of the stream's - // cancellation token, so a cancel fired from another thread while the - // fetch is in flight wins the race and unwinds the fetch (dropping its - // future at the await point) instead of waiting for it to complete. The - // token clone shares the same atomic state as the canceller's clone, so - // this observes a cancel fired at any instant. + // Pull the next owned batch from whichever backing shape this is. Both + // shapes run their batch fetch through the SAME cancellation wrapper + // (`select_next_batch`): a `tokio::select!` against a clone of the + // stream's cancellation token, so a cancel fired from another thread + // while the fetch is in flight wins the race and unwinds the fetch + // (dropping its future at the await point) instead of waiting for it to + // complete. Sharing one wrapper is deliberate (odbc#355 review F1): the + // cancellation/`select!` logic — the part under test — is then a single + // code path exercised by the Owned unit test, not duplicated per arm; the + // arms differ only in HOW they produce the batch future (the owned + // ResultStream vs the executed handle's drain-driven / lazy-CloudFetch + // next_batch) and the Executed arm's extra `executed_ref` stale-handle + // guard. let next: Option> = match shape { // Owned (metadata): drive the owned ResultStream lazily on the // runtime, one batch at a time, so an unbounded result streams @@ -312,31 +379,11 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( ResultStreamShape::Owned { stream, .. } => { match block_on_ffi(move || { let stream: &mut crate::result_stream::ResultStream = stream; - Box::pin(async move { - tokio::select! { - // Bias the fetch: if both are ready, prefer the batch - // so a completed fetch is not discarded by a cancel - // that arrived at the same instant. - biased; - fetched = stream.next_batch() => { - #[allow( - unreachable_patterns, - reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" - )] - match fetched? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(Error::not_implemented().message( - "metadata stream yielded a non-Arrow batch; the C ABI \ - exports Arrow only", - )), - None => Ok(None), - } - } - _ = cancel.cancelled() => Err(Error::cancelled() - .message("result stream cancelled during next_batch") - .with_retryable(false)), - } - }) + Box::pin(select_next_batch( + stream.next_batch(), + cancel, + "metadata stream", + )) }) { Ok(Some(rb)) => Some(Ok(rb)), Ok(None) => None, @@ -348,37 +395,16 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( Ok(e) => e, Err(code) => return code, }; - // Drive the executed handle's own next_batch so the - // drain-driven auto-close and lazy CloudFetch link fetches - // keep working. Convert the borrowed batch into an owned - // 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. + // Drive the executed handle's own next_batch so the drain-driven + // auto-close and lazy CloudFetch link fetches keep working. Same + // cancellation wrapper as the Owned arm above. match block_on_ffi(move || { let exec: &mut ExecutedStatement = exec; - Box::pin(async move { - tokio::select! { - biased; - fetched = exec.next_batch() => { - #[allow( - unreachable_patterns, - reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants" - )] - match fetched? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(Error::not_implemented().message( - "result stream yielded a non-Arrow batch; the C ABI \ - exports Arrow only", - )), - None => Ok(None), - } - } - _ = cancel.cancelled() => Err(Error::cancelled() - .message("result stream cancelled during next_batch") - .with_retryable(false)), - } - }) + Box::pin(select_next_batch( + exec.next_batch(), + cancel, + "result stream", + )) }) { Ok(Some(rb)) => Some(Ok(rb)), Ok(None) => None, From 5b4efa355f91360ff36da68d6d01fd5f9267ac3e Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 3 Sep 2026 09:59:13 +0000 Subject: [PATCH 4/4] fix(c-abi): wrap kernel_result_stream_canceller_new body in catch_ffi (odbc#355 review) Its two siblings (_cancel, _free) guard their bodies with catch_ffi so a panic cannot unwind across the extern "C" boundary (UB); _new did not, despite doing strictly more work (Box allocation + ptr::write). Wrap it too for panic-safety and uniformity. catch_ffi also clears the thread-local error up front, replacing the explicit clear_error(). No behavior change on the success/null-guard paths. Signed-off-by: Vikrant Puppala --- src/c_abi/result.rs | 46 +++++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 461e05d3..06befec9 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -491,26 +491,32 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_new( stream: *mut kernel_result_stream_t, out: *mut *mut kernel_result_stream_canceller_t, ) -> KernelStatusCode { - crate::c_abi::error::clear_error(); - if stream.is_null() { - return store_invalid_arg("kernel_result_stream_canceller_new: stream must not be null"); - } - if out.is_null() { - return store_invalid_arg("kernel_result_stream_canceller_new: out must not be null"); - } - // Read ONLY the `cancel` field through a raw-pointer projection — never a - // reference over the whole struct — so this is sound even while another - // thread holds `&mut (*p).shape` inside next_batch (disjoint fields; `cancel` - // is a `Sync` atomic). SAFETY: `stream` is a live box (non-null checked). - let p = stream as *mut ResultStreamInner; - let handle = ResultStreamCanceller { - cancel: (*std::ptr::addr_of!((*p).cancel)).clone(), - }; - std::ptr::write( - out, - Box::into_raw(Box::new(handle)) as *mut kernel_result_stream_canceller_t, - ); - KernelStatusCode::Success + // Wrap the body in catch_ffi (like _cancel / _free) so a panic — e.g. from the + // Box allocation — cannot unwind across the extern "C" boundary (UB); catch_ffi + // also clears the thread-local error up front (odbc#355 review). + catch_ffi(|| { + if stream.is_null() { + return store_invalid_arg( + "kernel_result_stream_canceller_new: stream must not be null", + ); + } + if out.is_null() { + return store_invalid_arg("kernel_result_stream_canceller_new: out must not be null"); + } + // Read ONLY the `cancel` field through a raw-pointer projection — never a + // reference over the whole struct — so this is sound even while another + // thread holds `&mut (*p).shape` inside next_batch (disjoint fields; `cancel` + // is a `Sync` atomic). SAFETY: `stream` is a live box (non-null checked). + let p = stream as *mut ResultStreamInner; + let handle = ResultStreamCanceller { + cancel: (*std::ptr::addr_of!((*p).cancel)).clone(), + }; + std::ptr::write( + out, + Box::into_raw(Box::new(handle)) as *mut kernel_result_stream_canceller_t, + ); + KernelStatusCode::Success + }) } /// Fire the cancellation of the result stream this canceller was created for