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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,12 @@ 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);
/* Fetch one batch without waiting. Success with ready=false means provider
* work is still pending and leaves the Arrow outputs untouched. Success with
* ready=true transfers a batch, or an empty array at end-of-stream. */
KernelStatusCode kernel_result_stream_try_next_batch(
kernel_result_stream_t* stream, bool* ready, struct ArrowArray* out_array,
struct ArrowSchema* out_schema);
KernelStatusCode kernel_result_stream_close(kernel_result_stream_t* stream);

/* ─── Result-stream cancellation (detached canceller) ─────────────────
Expand Down
193 changes: 193 additions & 0 deletions src/c_abi/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,81 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch(
})
}

/// Attempt to fetch one batch without waiting for provider progress.
///
/// # Safety
/// `stream` must be a live result-stream handle from a `kernel_*` call that
/// produces one, and not previously closed; `ready`, `out_array`, and
/// `out_schema` must be valid, writable pointers. On `Success` with
/// `*ready == true` the Arrow outputs are transferred to the caller (an
/// end-of-stream yields a released array); with `*ready == false` they are left
/// untouched.
#[no_mangle]
pub unsafe extern "C" fn kernel_result_stream_try_next_batch(
stream: *mut kernel_result_stream_t,
ready: *mut bool,
out_array: *mut FFI_ArrowArray,
out_schema: *mut FFI_ArrowSchema,
) -> KernelStatusCode {
catch_ffi(|| {
if stream.is_null() || ready.is_null() || out_array.is_null() || out_schema.is_null() {
return store_invalid_arg("try_next_batch: pointers must not be null");
}
std::ptr::write(ready, false);
let inner = stream as *mut ResultStreamInner;
if (*std::ptr::addr_of!((*inner).cancel)).is_cancelled() {
return store_and_code(
Error::cancelled()
.message("result stream was cancelled")
.with_retryable(false),
);
}
let shape = &mut *std::ptr::addr_of_mut!((*inner).shape);
let outcome = match shape {
ResultStreamShape::Owned { stream, .. } => stream.try_next_batch(),
ResultStreamShape::Executed { exec, valid } => {
let exec = match executed_ref(*exec, valid) {
Ok(exec) => exec,
Err(code) => return code,
};
exec.try_next_batch()
}
};
match outcome {
Ok(crate::result_stream::TryNextBatch::Pending) => KernelStatusCode::Success,
Ok(crate::result_stream::TryNextBatch::End) => {
std::ptr::write(ready, true);
std::ptr::write(out_array, FFI_ArrowArray::empty());
std::ptr::write(out_schema, FFI_ArrowSchema::empty());
KernelStatusCode::Success
}
Ok(crate::result_stream::TryNextBatch::Ready(batch)) => {
#[allow(
unreachable_patterns,
reason = "forward-compat fallback for future #[non_exhaustive] ResultBatch variants"
)]
let arrow = match batch {
ResultBatch::Arrow(batch) => batch,
_ => return store_and_code(Error::not_implemented().message(
"try_next_batch yielded a non-Arrow batch; the C ABI exports Arrow only",
)),
};
let struct_array: arrow_array::StructArray = arrow.clone().into();
match arrow_array::ffi::to_ffi(&struct_array.into_data()) {
Ok((array, schema)) => {
std::ptr::write(ready, true);
std::ptr::write(out_array, array);
std::ptr::write(out_schema, schema);
KernelStatusCode::Success
}
Err(error) => store_and_code(Error::from(error)),
}
}
Err(error) => store_and_code(error),
}
})
}

/// Free client-side resources held by the stream. Local-only; issues no
/// server RPC. For the **executed** shape this frees only the borrow
/// wrapper, not the executed handle itself (close that separately via
Expand Down Expand Up @@ -646,6 +721,124 @@ mod tests {

let rc = unsafe { kernel_result_stream_close(std::ptr::null_mut()) };
assert_eq!(rc, KernelStatusCode::InvalidArgument);

let mut ready = false;
let rc = unsafe {
kernel_result_stream_try_next_batch(
std::ptr::null_mut(),
&mut ready,
&mut arr,
&mut sch,
)
};
assert_eq!(rc, KernelStatusCode::InvalidArgument);
}

#[test]
fn try_next_batch_returns_ready_batch_then_end() {
let (schema, batch) = one_row_batch();
let stream = owned_stream_over(schema, vec![batch]);
let mut ready = false;
let mut arr = FFI_ArrowArray::empty();
let mut sch = FFI_ArrowSchema::empty();
assert_eq!(
unsafe { kernel_result_stream_try_next_batch(stream, &mut ready, &mut arr, &mut sch) },
KernelStatusCode::Success
);
assert!(ready);
assert!(!arr.is_released());

ready = false;
assert_eq!(
unsafe { kernel_result_stream_try_next_batch(stream, &mut ready, &mut arr, &mut sch) },
KernelStatusCode::Success
);
assert!(ready);
assert!(arr.is_released());
unsafe { kernel_result_stream_close(stream) };
}

#[test]
fn try_next_batch_reports_pending_without_entering_async_reader() {
use crate::reader::test_utils::BlockingReader;
use crate::result_stream::ResultStream;

let schema: SchemaRef =
Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let entered = Arc::new(tokio::sync::Notify::new());
let reader = BlockingReader {
schema: schema.clone(),
entered: entered.clone(),
release: Arc::new(tokio::sync::Notify::new()),
};
let rt = tokio::runtime::Runtime::new().unwrap();
let result_stream =
rt.block_on(async { ResultStream::from_reader(Box::new(reader)).await.unwrap() });
let stream = into_raw_result_stream(schema, result_stream);

let mut ready = true;
let mut arr = FFI_ArrowArray::empty();
let mut sch = FFI_ArrowSchema::empty();
assert_eq!(
unsafe { kernel_result_stream_try_next_batch(stream, &mut ready, &mut arr, &mut sch) },
KernelStatusCode::Success
);
assert!(!ready);
unsafe { kernel_result_stream_close(stream) };
}

/// A reader that errors on fetch must surface the TYPED error on the
/// caller thread: `try_next_batch` returns the mapped status code AND
/// `kernel_get_last_error` reports the structured fields (code / message /
/// retryable). This pins the `Err(error) => store_and_code(error)` branch —
/// a regression that dropped the error (falling through with no
/// `kernel_get_last_error` detail) or lost the typed fields would pass CI
/// otherwise.
#[test]
fn try_next_batch_surfaces_typed_error_on_caller_thread() {
use crate::reader::test_utils::ErrorReader;
use crate::result_stream::ResultStream;

let schema: SchemaRef =
Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let rt = tokio::runtime::Runtime::new().unwrap();
let result_stream = rt.block_on(async {
ResultStream::from_reader(Box::new(ErrorReader {
schema: schema.clone(),
}))
.await
.unwrap()
});
let stream = into_raw_result_stream(schema, result_stream);

let mut ready = true;
let mut arr = FFI_ArrowArray::empty();
let mut sch = FFI_ArrowSchema::empty();
// `Error::io()` maps to `ErrorCode::Internal` -> `KernelStatusCode::Internal`.
let rc =
unsafe { kernel_result_stream_try_next_batch(stream, &mut ready, &mut arr, &mut sch) };
assert_eq!(rc, KernelStatusCode::Internal);
assert!(!ready, "a failing fetch must not report a ready batch");
assert!(arr.is_released(), "no array should be handed out on error");

// The typed error must be retrievable on THIS (caller) thread.
let mut err = std::mem::MaybeUninit::<crate::c_abi::error::KernelError>::uninit();
let present = unsafe { crate::c_abi::error::kernel_get_last_error(err.as_mut_ptr()) };
assert!(
present,
"a typed error must be recorded after a failed fetch"
);
let err = unsafe { err.assume_init() };
assert_eq!(err.code, KernelStatusCode::Internal as i32);
let msg = unsafe { std::ffi::CStr::from_ptr(err.message) }
.to_str()
.unwrap();
assert!(
msg.contains("simulated read error"),
"message should round-trip the reader's error, got: {msg}"
);

unsafe { kernel_result_stream_close(stream) };
}

/// Canceller null guards (odbc#355-B).
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ pub use kernel_error::{Error, ErrorCode, Result};
/// kernel actually emits. See [`klog::KERNEL_LOG_TARGET`].
pub use klog::KERNEL_LOG_TARGET;
pub use metadata_v0::{Identifier, LikePattern, Metadata};
pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRef};
pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRef, TryNextBatch};
pub use session::{Session, SessionBuilder};
pub use statement::executed::ExecutedStatement;
pub use statement::executed_async::{
Expand Down
12 changes: 11 additions & 1 deletion src/metadata/thrift_shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1215,6 +1215,10 @@ impl ThriftReshapingReader {
reshape,
}
}

fn reshape_batch(&self, batch: RecordBatch) -> Result<RecordBatch> {
(self.reshape)(&batch)
}
}

#[async_trait::async_trait]
Expand All @@ -1225,10 +1229,16 @@ impl ResultReader for ThriftReshapingReader {

async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
match self.upstream.next_batch().await? {
Some(b) => Ok(Some((self.reshape)(&b)?)),
Some(batch) => Ok(Some(self.reshape_batch(batch)?)),
None => Ok(None),
}
}

fn try_next_batch(&mut self) -> Result<crate::reader::TryNextBatch> {
self.upstream
.try_next_batch()?
.map_ready(|batch| self.reshape_batch(batch))
}
}

#[cfg(test)]
Expand Down
Loading
Loading