diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 285f35b5..8ff64bca 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -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) ───────────────── diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 06befec9..1c66a033 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -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 @@ -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::::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). diff --git a/src/lib.rs b/src/lib.rs index 7661bc0b..2570f3f4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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::{ diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index be5261c9..3b806328 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -1215,6 +1215,10 @@ impl ThriftReshapingReader { reshape, } } + + fn reshape_batch(&self, batch: RecordBatch) -> Result { + (self.reshape)(&batch) + } } #[async_trait::async_trait] @@ -1225,10 +1229,16 @@ impl ResultReader for ThriftReshapingReader { async fn next_batch(&mut self) -> Result> { 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 { + self.upstream + .try_next_batch()? + .map_ready(|batch| self.reshape_batch(batch)) + } } #[cfg(test)] diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index aefd7b51..04822874 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -494,9 +494,7 @@ impl StreamingCloudFetchProvider { } // Drain batch buffer first - if let Some(batch) = self.current_batch_buffer.lock().unwrap().pop_front() { - // Capture schema from first batch - let _ = self.schema.get_or_init(|| batch.schema()); + if let Some(batch) = self.take_buffered_batch() { return Ok(Some(batch)); } @@ -504,7 +502,7 @@ impl StreamingCloudFetchProvider { let chunk_index = self.current_chunk_index.load(Ordering::Acquire); // Check if we've reached end of stream - if self.end_of_stream.load(Ordering::Acquire) && !self.chunks.contains_key(&chunk_index) { + if self.is_at_end(chunk_index) { debug!("End of stream reached at chunk {}", chunk_index); return Ok(None); } @@ -513,32 +511,12 @@ impl StreamingCloudFetchProvider { self.wait_for_chunk(chunk_index).await?; // Get the chunk and move batches to buffer - if let Some((_, mut entry)) = self.chunks.remove(&chunk_index) { - if let Some(batches) = entry.batches.take() { - let mut buffer = self.current_batch_buffer.lock().unwrap(); - for batch in batches { - buffer.push_back(batch); - } - } - - // Mark chunk as released and decrement counter - let new_count = self.chunks_in_memory.fetch_sub(1, Ordering::Release) - 1; - - // Move to next chunk - let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1; - self.metrics.record_chunk_iterated(); - - debug!( - "Released chunk {}: chunks_in_memory={}/{}, consumer advancing to {}", - chunk_index, new_count, self.max_chunks_in_memory, next_chunk - ); - + if self.release_downloaded_chunk(chunk_index) { // Schedule more downloads self.schedule_downloads().await; // Return first batch from buffer - if let Some(batch) = self.current_batch_buffer.lock().unwrap().pop_front() { - let _ = self.schema.get_or_init(|| batch.schema()); + if let Some(batch) = self.take_buffered_batch() { return Ok(Some(batch)); } } @@ -558,6 +536,86 @@ impl StreamingCloudFetchProvider { Err(Error::invalid_state().message(format!("Chunk {} not found after wait", chunk_index))) } + /// Return the next batch if it is already downloaded, without waiting for + /// chunk state to change. Download and link-fetch tasks continue on the + /// provider runtime while this returns `Pending` to the caller. + pub fn try_next_batch(self: &Arc) -> Result { + use crate::reader::TryNextBatch; + + let mut released = false; + let outcome = loop { + if self.cancel_token.is_cancelled() { + break Err(Error::invalid_state().message("Operation cancelled")); + } + + if let Some(batch) = self.take_buffered_batch() { + break Ok(TryNextBatch::Ready(batch)); + } + + let chunk_index = self.current_chunk_index.load(Ordering::Acquire); + if self.is_at_end(chunk_index) { + break Ok(TryNextBatch::End); + } + + let ready = if let Some(entry) = self.chunks.get(&chunk_index) { + match &entry.state { + ChunkState::Downloaded => true, + ChunkState::DownloadFailed(error) => break Err(error.clone()), + ChunkState::ProcessingFailed(error) => { + break Err(Error::io().message(error.clone())) + } + ChunkState::Cancelled => { + break Err(Error::invalid_state().message("Operation cancelled")) + } + _ => false, + } + } else { + false + }; + + if !ready { + if let Some(error) = self.terminal_error() { + break Err(error); + } + break Ok(TryNextBatch::Pending); + } + + // Only the single result consumer removes chunks. Once a chunk is + // Downloaded its entry is terminal, so the remove cannot race a + // downloader changing it back to an earlier state. + if !self.release_downloaded_chunk(chunk_index) { + break Ok(TryNextBatch::Pending); + } + released = true; + // Loop once to return the first batch, or advance across an empty + // downloaded chunk to Pending/End/the following ready chunk. + }; + + // Refill the rolling window once, after the loop settles, rather than + // once per skipped empty chunk. Any released chunk freed a window slot; + // schedule_downloads early-exits when the window is full and the current + // batch (if any) is already buffered, so this must not block. + if released { + // Detached spawn (vs. the blocking path's inline await) means two + // rapid try_next_batch calls can overlap this refill, and a mixed + // try_next_batch + next_batch caller can run it alongside next_batch's + // inline refill. That is safe because schedule_downloads is + // reentrant against itself: the load of next_download_index is only + // a hint. The actual claim is the UrlFetched -> Downloading + // transition performed under the DashMap get_mut write guard, so at + // most one runner ever claims a given chunk. A runner that loses the + // race sees a non-UrlFetched state, fails the claim, and breaks + // without advancing next_download_index (only the winner fetch_adds + // it), so no index is double-scheduled or skipped. + let provider = Arc::clone(self); + self.runtime_handle.spawn(async move { + provider.schedule_downloads().await; + }); + } + + outcome + } + /// Cancel all pending operations. pub fn cancel(&self) { debug!("Cancelling CloudFetch provider"); @@ -567,6 +625,36 @@ impl StreamingCloudFetchProvider { // --- Internal methods --- + fn take_buffered_batch(&self) -> Option { + let batch = self.current_batch_buffer.lock().unwrap().pop_front()?; + let _ = self.schema.get_or_init(|| batch.schema()); + Some(batch) + } + + fn is_at_end(&self, chunk_index: i64) -> bool { + self.end_of_stream.load(Ordering::Acquire) && !self.chunks.contains_key(&chunk_index) + } + + /// Move one downloaded chunk into the consumer buffer and advance the + /// shared cursor. Scheduling the replacement download remains caller-owned + /// because the blocking path awaits it while the non-blocking path spawns it. + fn release_downloaded_chunk(&self, chunk_index: i64) -> bool { + let Some((_, mut entry)) = self.chunks.remove(&chunk_index) else { + return false; + }; + if let Some(batches) = entry.batches.take() { + self.current_batch_buffer.lock().unwrap().extend(batches); + } + let new_count = self.chunks_in_memory.fetch_sub(1, Ordering::Release) - 1; + let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1; + self.metrics.record_chunk_iterated(); + debug!( + "Released chunk {}: chunks_in_memory={}/{}, consumer advancing to {}", + chunk_index, new_count, self.max_chunks_in_memory, next_chunk + ); + true + } + /// Record the first terminal link-fetch failure and wake every waiter. /// /// Called from the link-fetch error paths once the transport's @@ -2382,6 +2470,214 @@ mod tests { } } + /// Build a downloader that is never exercised by the non-blocking + /// consumer-path tests below (they seed chunk state directly and set + /// `end_of_stream`, so the spawned `schedule_downloads` refill exits + /// without issuing an RPC). Points at an unroutable URL and disables + /// retries so any accidental download fails fast rather than hanging. + fn unused_downloader() -> Arc { + use crate::client::retry::{build_retry_configs, RetryConfig}; + use crate::client::{DatabricksHttpClient, HttpClientConfig}; + use crate::types::sea::CompressionCodec; + + let retry = RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }; + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .unwrap(), + ); + Arc::new(ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + )) + } + + /// `try_next_batch` must return `Pending` (without blocking) while the + /// head chunk is not yet `Downloaded`, then `Ready` once it flips, and + /// finally `End` after the last chunk is consumed. This exercises the + /// non-blocking chunk-state machine that diverges from `next_batch`. + #[tokio::test] + async fn try_next_batch_pending_then_ready_then_end() { + use crate::reader::TryNextBatch; + + let chunks: Arc> = Arc::new(DashMap::new()); + // Chunk 0 present but still downloading — not ready to yield. + chunks.insert( + 0, + entry_with_state(create_test_link(0), ChunkState::Downloading), + ); + let fetcher: Arc = Arc::new(MockLinkFetcher::new(1)); + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + fetcher, + unused_downloader(), + Arc::clone(&chunks), + /* end_of_stream = */ true, + ); + // One chunk resident: `release_downloaded_chunk` decrements this. + provider.chunks_in_memory.store(1, Ordering::Release); + + // Not downloaded yet → Pending, and it must NOT block. + assert!( + matches!(provider.try_next_batch().unwrap(), TryNextBatch::Pending), + "a not-yet-Downloaded head chunk must report Pending" + ); + + // Flip the chunk to Downloaded with real batches, as a download + // task would. + { + let mut entry = chunks.get_mut(&0).unwrap(); + entry.state = ChunkState::Downloaded; + entry.batches = Some(vec![make_batch(&[1, 2, 3])]); + } + + match provider.try_next_batch().unwrap() { + TryNextBatch::Ready(batch) => assert_eq!(batch.num_rows(), 3), + _ => panic!("expected Ready after chunk flipped to Downloaded"), + } + + // Head chunk consumed; end_of_stream + no more chunks → End. + assert!( + matches!(provider.try_next_batch().unwrap(), TryNextBatch::End), + "after the only chunk is drained the stream must report End" + ); + } + + /// A `Downloaded` chunk that decoded to zero batches must be skipped + /// (the cursor advancing past it) so the caller sees the *next* + /// chunk's data — not a spurious `Pending`/`End`. Guards the + /// empty-downloaded-chunk skip in the non-blocking loop. + #[tokio::test] + async fn try_next_batch_skips_empty_downloaded_chunk() { + use crate::reader::TryNextBatch; + + let chunks: Arc> = Arc::new(DashMap::new()); + // Chunk 0: Downloaded but empty (legal on paginated results). + chunks.insert( + 0, + ChunkEntry { + link: Some(create_test_link(0)), + state: ChunkState::Downloaded, + batches: Some(vec![]), + last_failure_reason: None, + }, + ); + // Chunk 1: Downloaded with real data. + chunks.insert( + 1, + ChunkEntry { + link: Some(create_test_link(1)), + state: ChunkState::Downloaded, + batches: Some(vec![make_batch(&[7, 8])]), + last_failure_reason: None, + }, + ); + let fetcher: Arc = Arc::new(MockLinkFetcher::new(2)); + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + fetcher, + unused_downloader(), + Arc::clone(&chunks), + /* end_of_stream = */ true, + ); + provider.chunks_in_memory.store(2, Ordering::Release); + + // The empty chunk 0 must not stall the stream: the loop advances + // past it and yields chunk 1's batch in a single call. + match provider.try_next_batch().unwrap() { + TryNextBatch::Ready(batch) => assert_eq!(batch.num_rows(), 2), + _ => panic!("empty chunk must be skipped to reach chunk 1"), + } + assert!( + matches!(provider.try_next_batch().unwrap(), TryNextBatch::End), + "both chunks consumed → End" + ); + } + + /// A terminal per-chunk failure at the head must surface as `Err` + /// (not `Pending`/`End`) so the non-blocking caller sees the real + /// cause deterministically. `DownloadFailed` carries a typed error + /// that must be returned verbatim; `ProcessingFailed` carries a + /// message that is re-wrapped as `Error::io()`. + #[tokio::test] + async fn try_next_batch_surfaces_terminal_chunk_errors() { + use crate::kernel_error::ErrorCode; + + // DownloadFailed → the carried typed error is returned as-is, + // preserving its classification and retryable flag. + { + let chunks: Arc> = Arc::new(DashMap::new()); + let download_err = Error::network_error().message("chunk 0 download blew up"); + assert_eq!(download_err.code, ErrorCode::NetworkError); + chunks.insert( + 0, + entry_with_state( + create_test_link(0), + ChunkState::DownloadFailed(download_err), + ), + ); + let fetcher: Arc = Arc::new(MockLinkFetcher::new(1)); + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + fetcher, + unused_downloader(), + Arc::clone(&chunks), + /* end_of_stream = */ true, + ); + + let err = match provider.try_next_batch() { + Err(err) => err, + Ok(_) => panic!("a DownloadFailed head chunk must surface an error"), + }; + assert_eq!( + err.code, + ErrorCode::NetworkError, + "DownloadFailed must return its carried error verbatim, got: {err}" + ); + assert!( + err.message.contains("chunk 0 download blew up"), + "the original download error message must be preserved: {err}" + ); + } + + // ProcessingFailed → the carried message is re-wrapped as an + // I/O error (ErrorCode::Internal). + { + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert( + 0, + entry_with_state( + create_test_link(0), + ChunkState::ProcessingFailed("arrow decode failed".to_string()), + ), + ); + let fetcher: Arc = Arc::new(MockLinkFetcher::new(1)); + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + fetcher, + unused_downloader(), + Arc::clone(&chunks), + /* end_of_stream = */ true, + ); + + let err = match provider.try_next_batch() { + Err(err) => err, + Ok(_) => panic!("a ProcessingFailed head chunk must surface an error"), + }; + assert_eq!( + err.code, + ErrorCode::Internal, + "ProcessingFailed must be re-wrapped as an I/O error, got: {err}" + ); + assert!( + err.message.contains("arrow decode failed"), + "the original processing error message must be preserved: {err}" + ); + } + } + #[tokio::test] async fn refresh_batch_updates_link_for_urlfetched_chunks() { // Chunks 0-2 all expired, all in UrlFetched state. One diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index fad6cf68..57e4158a 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -163,6 +163,40 @@ struct ConsumerState { sticky_error: Option, } +impl ConsumerState { + fn take_buffered_batch(&mut self) -> Option { + let current = self.current.as_ref()?; + if self.cursor < current.batches.len() { + let batch = current.batches[self.cursor].clone(); + self.cursor += 1; + return Some(batch); + } + debug!( + "Drained inline chunk {} ({} batches)", + current.chunk_index, + current.batches.len(), + ); + self.current = None; + self.cursor = 0; + None + } + + /// Install one channel item. Returns false for clean end-of-stream. + fn accept_chunk(&mut self, item: Option>) -> Result { + match item { + Some(Ok(entry)) => { + self.current = Some(entry); + Ok(true) + } + Some(Err(error)) => { + self.sticky_error = Some(error.clone()); + Err(error) + } + None => Ok(false), + } + } +} + impl InlineStreamingProvider { /// Build a streaming provider seeded by the first chunk's payload /// (which the kernel already received in the initial execute @@ -302,20 +336,8 @@ impl InlineStreamingProvider { // error surfaces. Only when no more buffered data is // available do we consult the sticky-error slot or the // channel. - if let Some(ref current) = state.current { - if state.cursor < current.batches.len() { - let batch = current.batches[state.cursor].clone(); - state.cursor += 1; - return Ok(Some(batch)); - } - // Current chunk fully drained; advance. - debug!( - "Drained inline chunk {} ({} batches)", - current.chunk_index, - current.batches.len(), - ); - state.current = None; - state.cursor = 0; + if let Some(batch) = state.take_buffered_batch() { + return Ok(Some(batch)); } // Buffered chunk is drained. Sticky-error short- @@ -327,20 +349,37 @@ impl InlineStreamingProvider { } // Need to recv the next chunk from the prefetch task. - match state.rx.recv().await { - Some(Ok(entry)) => { - state.current = Some(entry); - // Loop back to drain. - } - Some(Err(e)) => { - // Store sticky and surface on this call. - state.sticky_error = Some(e.clone()); - return Err(e); - } - None => { - // Channel closed: clean EOS. - return Ok(None); + let item = state.rx.recv().await; + if !state.accept_chunk(item)? { + return Ok(None); + } + } + } + + /// Return a buffered batch without waiting for the prefetch task. + pub(crate) fn try_next_batch(&self) -> Result { + use crate::reader::TryNextBatch; + use tokio::sync::mpsc::error::TryRecvError; + + let Ok(mut state) = self.consumer.try_lock() else { + return Ok(TryNextBatch::Pending); + }; + loop { + if let Some(batch) = state.take_buffered_batch() { + return Ok(TryNextBatch::Ready(batch)); + } + + if let Some(ref error) = state.sticky_error { + return Err(error.clone()); + } + + let item = state.rx.try_recv(); + match item { + Ok(item) => { + state.accept_chunk(Some(item))?; } + Err(TryRecvError::Empty) => return Ok(TryNextBatch::Pending), + Err(TryRecvError::Disconnected) => return Ok(TryNextBatch::End), } } } @@ -1092,4 +1131,141 @@ mod tests { assert_eq!(total_batches, 5, "all 5 chunks must arrive after resume"); assert_eq!(mock.call_count(), 4, "exactly 4 RPCs total (chunks 1-4)"); } + + /// Non-blocking `try_next_batch`: a buffered batch is returned as + /// `Ready` without awaiting the prefetch task, and once the single + /// chunk is drained the closed channel surfaces as `End` + /// (`TryRecvError::Disconnected`). + #[tokio::test] + async fn try_next_batch_ready_then_end_on_disconnect() { + use crate::reader::TryNextBatch; + + // Single-chunk result (next_chunk_index = None): the provider + // drops the sender, so after the initial chunk drains the + // receiver observes Disconnected. + let mock = MockSource::new(vec![]); + let source: Arc = mock.clone(); + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + build_ipc_bytes(&[10, 20]), + 0, // initial_chunk_index + 0, // initial_row_offset + 2, // initial_row_count + None, + CompressionCodec::None, + 4, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + match provider.try_next_batch().unwrap() { + TryNextBatch::Ready(batch) => assert_eq!(batch.num_rows(), 2), + _ => panic!("buffered initial chunk must be Ready without awaiting prefetch"), + } + assert!( + matches!(provider.try_next_batch().unwrap(), TryNextBatch::End), + "drained single-chunk stream → closed channel → End" + ); + assert_eq!(mock.call_count(), 0, "no prefetch RPC for a single chunk"); + } + + /// When another task holds the consumer lock, `try_next_batch` must + /// report `Pending` immediately (via `try_lock` failing) rather than + /// blocking on the lock. + #[tokio::test] + async fn try_next_batch_pending_on_lock_contention() { + use crate::reader::TryNextBatch; + + let mock = MockSource::new(vec![]); + let source: Arc = mock.clone(); + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + build_ipc_bytes(&[1]), + 0, + 0, + 1, + None, + CompressionCodec::None, + 4, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // Hold the consumer lock so try_next_batch's try_lock fails. + let guard = provider.consumer.lock().await; + assert!( + matches!(provider.try_next_batch().unwrap(), TryNextBatch::Pending), + "contended consumer lock must yield Pending, not block" + ); + drop(guard); + + // Once released the buffered batch becomes available. + match provider.try_next_batch().unwrap() { + TryNextBatch::Ready(batch) => assert_eq!(batch.num_rows(), 1), + _ => panic!("after lock released the buffered batch must be Ready"), + } + } + + /// Non-blocking `try_next_batch`: when the channel is open but + /// empty (the prefetch task is parked mid-RPC and hasn't delivered + /// the next chunk yet), `try_recv` yields `TryRecvError::Empty`, + /// which must map to `Pending` — never `End` — and must not block. + /// This is the branch the blocking `next_batch` cannot exercise, + /// so it needs its own guard. + #[tokio::test] + async fn try_next_batch_pending_on_empty_open_channel() { + use crate::reader::TryNextBatch; + + // A source whose RPC never completes: once the initial chunk + // drains, the prefetch task is parked inside `get_inline_chunk`, + // so the sender stays alive (channel open) but nothing is ever + // delivered (channel empty) — deterministically the `Empty` + // case regardless of task scheduling. + #[derive(Debug)] + struct StalledSource; + #[async_trait] + impl InlineChunkSource for StalledSource { + async fn get_inline_chunk( + &self, + _statement_id: &str, + _chunk_index: i64, + _row_offset: i64, + ) -> Result { + std::future::pending().await + } + } + + let source: Arc = Arc::new(StalledSource); + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + build_ipc_bytes(&[7, 8]), + 0, // initial_chunk_index + 0, // initial_row_offset + 2, // initial_row_count + Some(1), // more chunks → prefetch task spawned, sender stays alive + CompressionCodec::None, + 4, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // Drain the buffered initial chunk. + match provider.try_next_batch().unwrap() { + TryNextBatch::Ready(batch) => assert_eq!(batch.num_rows(), 2), + _ => panic!("buffered initial chunk must be Ready"), + } + + // Channel is open (prefetch task parked in the RPC) but empty: + // must be Pending, and must not block. + assert!( + matches!(provider.try_next_batch().unwrap(), TryNextBatch::Pending), + "open-but-empty channel → TryRecvError::Empty → Pending" + ); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index b7683e4d..59f6d533 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -648,6 +648,18 @@ pub trait ResultReader: Send + Sync { /// Get the next record batch, or None if end of results. async fn next_batch(&mut self) -> Result>; + /// Return the next batch if it is already available without waiting. + /// + /// Every reader intended to back a non-blocking [`ResultStream`] MUST + /// override this method. The default returns an `invalid_state` error at + /// runtime rather than failing to compile, so a newly added reader that + /// forgets to override it will only surface the omission when + /// `ResultStream::try_next_batch` is called. Leave the default in place + /// only as a deliberate opt-out for readers that genuinely cannot poll. + fn try_next_batch(&mut self) -> Result { + Err(Error::invalid_state().message("reader does not support non-blocking batch reads")) + } + /// Optional reader-level metrics accumulated below `ResultStream`. /// /// CloudFetch overrides this to surface chunk download metrics into @@ -657,6 +669,37 @@ pub trait ResultReader: Send + Sync { } } +/// Result of a non-blocking batch read. +#[derive(Debug)] +#[non_exhaustive] +pub enum TryNextBatch { + Ready(RecordBatch), + Pending, + End, +} + +impl TryNextBatch { + /// Convert the blocking reader representation into the non-blocking one. + pub(crate) fn from_option(batch: Option) -> Self { + match batch { + Some(batch) => Self::Ready(batch), + None => Self::End, + } + } + + /// Transform a ready batch while preserving pending and end states. + pub(crate) fn map_ready( + self, + transform: impl FnOnce(RecordBatch) -> Result, + ) -> Result { + Ok(match self { + Self::Ready(batch) => Self::Ready(transform(batch)?), + Self::Pending => Self::Pending, + Self::End => Self::End, + }) + } +} + #[non_exhaustive] #[derive(Debug, Clone, Copy, Default)] pub struct ResultReaderMetrics { @@ -688,6 +731,10 @@ impl ResultReader for CloudFetchResultReader { self.provider.next_batch().await } + fn try_next_batch(&mut self) -> Result { + self.provider.try_next_batch() + } + fn metrics(&self) -> Option { self.provider.metrics() } @@ -720,6 +767,10 @@ impl ResultReader for InlineArrowReader { async fn next_batch(&mut self) -> Result> { self.provider.next_batch() } + + fn try_next_batch(&mut self) -> Result { + Ok(TryNextBatch::from_option(self.provider.next_batch()?)) + } } /// Reader for multi-chunk inline-Arrow streaming. @@ -752,6 +803,10 @@ impl ResultReader for InlineStreamingReader { async fn next_batch(&mut self) -> Result> { self.provider.next_batch().await } + + fn try_next_batch(&mut self) -> Result { + self.provider.try_next_batch() + } } /// In-memory result reader. @@ -787,6 +842,10 @@ impl ResultReader for InMemoryReader { async fn next_batch(&mut self) -> Result> { Ok(self.batches.next()) } + + fn try_next_batch(&mut self) -> Result { + Ok(TryNextBatch::from_option(self.batches.next())) + } } /// Empty reader for queries with no results. @@ -813,6 +872,10 @@ impl ResultReader for EmptyReader { async fn next_batch(&mut self) -> Result> { Ok(None) } + + fn try_next_batch(&mut self) -> Result { + Ok(TryNextBatch::End) + } } /// Arrow field metadata keys for Databricks column information. diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 94a4b833..155cb8f6 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -38,7 +38,7 @@ mod json; use crate::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; -use crate::reader::{ResultReader, ResultReaderAdapter, ResultReaderMetrics}; +use crate::reader::{ResultReader, ResultReaderAdapter, ResultReaderMetrics, TryNextBatch}; use crate::types::sea::ResultManifest; use arrow_array::builder::StringBuilder; use arrow_array::{ArrayRef, RecordBatch}; @@ -97,6 +97,13 @@ pub(crate) struct ResultPostProcessor { type BatchTransform = Box Result + Send + Sync>; impl ResultPostProcessor { + fn process_batch(&self, batch: RecordBatch) -> Result { + match &self.transform { + Some(transform) => transform(&batch), + None => Ok(batch), + } + } + /// Build a post-processor around `inner`. /// /// `manifest` is the SEA `ResultManifest` carrying server-reported @@ -285,10 +292,12 @@ impl ResultReader for ResultPostProcessor { let Some(batch) = self.inner.next_batch().await? else { return Ok(None); }; - match &self.transform { - Some(t) => Ok(Some(t(&batch)?)), - None => Ok(Some(batch)), - } + Ok(Some(self.process_batch(batch)?)) + } + + fn try_next_batch(&mut self) -> Result { + let next = self.inner.try_next_batch()?; + next.map_ready(|batch| self.process_batch(batch)) } fn metrics(&self) -> Option { diff --git a/src/reader/test_utils.rs b/src/reader/test_utils.rs index f4657b0a..2b3dbb94 100644 --- a/src/reader/test_utils.rs +++ b/src/reader/test_utils.rs @@ -59,6 +59,16 @@ impl ResultReader for MockReader { Ok(Some(batch)) } } + + fn try_next_batch(&mut self) -> Result { + Ok(if self.index >= self.batches.len() { + crate::reader::TryNextBatch::End + } else { + let batch = self.batches[self.index].clone(); + self.index += 1; + crate::reader::TryNextBatch::Ready(batch) + }) + } } /// A reader that returns an error on `next_batch()`. @@ -75,6 +85,10 @@ impl ResultReader for ErrorReader { async fn next_batch(&mut self) -> Result> { Err(Error::io().message("simulated read error")) } + + fn try_next_batch(&mut self) -> Result { + Err(Error::io().message("simulated read error")) + } } /// A reader that yields one successful batch, then errors on the @@ -99,6 +113,13 @@ impl ResultReader for BatchThenErrorReader { None => Err(Error::io().message("simulated read error after first batch")), } } + + fn try_next_batch(&mut self) -> Result { + match self.batch.take() { + Some(batch) => Ok(crate::reader::TryNextBatch::Ready(batch)), + None => Err(Error::io().message("simulated read error after first batch")), + } + } } /// A reader whose `next_batch()` blocks indefinitely until explicitly @@ -133,6 +154,10 @@ impl ResultReader for BlockingReader { self.release.notified().await; Ok(None) } + + fn try_next_batch(&mut self) -> Result { + Ok(crate::reader::TryNextBatch::Pending) + } } /// A reader that returns an error on `schema()`. @@ -147,4 +172,8 @@ impl ResultReader for SchemaErrorReader { async fn next_batch(&mut self) -> Result> { Ok(None) } + + fn try_next_batch(&mut self) -> Result { + Ok(crate::reader::TryNextBatch::End) + } } diff --git a/src/result_stream.rs b/src/result_stream.rs index 35252726..7a2a8495 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -73,6 +73,7 @@ pub type SchemaRef = Arc; /// non-Arrow variants (`ColumnarThrift`, `JsonRows`, …) are additive /// — wrappers writing `match` against `ResultBatch` get a forced /// `_ =>` arm that keeps compiling. +#[derive(Debug)] #[non_exhaustive] pub enum ResultBatch { /// Arrow `RecordBatch`. @@ -80,6 +81,15 @@ pub enum ResultBatch { // Future: ColumnarThrift(...), JsonRows(...) } +/// Outcome of a non-blocking result-stream read. +#[derive(Debug)] +#[non_exhaustive] +pub enum TryNextBatch<'a> { + Ready(&'a ResultBatch), + Pending, + End, +} + // `ResultBatch::into_arrow()` was deliberately removed: the // `#[non_exhaustive]` envelope is the right escape hatch already. // Wrappers `match` directly on `ResultBatch::Arrow(rb)` and choose @@ -738,6 +748,46 @@ impl ResultStream { } } + /// Return the next batch if it is already available without waiting for + /// network or background-prefetch progress. + pub fn try_next_batch(&mut self) -> Result> { + if let Some(batch) = self.prefetched.take() { + self.set_current_batch(batch); + return Ok(TryNextBatch::Ready( + self.current.as_ref().expect("batch was just installed"), + )); + } + if self.exhausted { + self.finalize_telemetry(None); + return Ok(TryNextBatch::End); + } + + let reader = self + .reader + .as_mut() + .expect("ResultStream reader is present until into_owned_batches consumes it"); + match reader.try_next_batch() { + Ok(crate::reader::TryNextBatch::Ready(batch)) => { + self.set_current_batch(ResultBatch::Arrow(batch)); + Ok(TryNextBatch::Ready( + self.current.as_ref().expect("batch was just installed"), + )) + } + Ok(crate::reader::TryNextBatch::Pending) => Ok(TryNextBatch::Pending), + Ok(crate::reader::TryNextBatch::End) => { + self.current = None; + self.current_row_idx = 0; + self.exhausted = true; + self.finalize_telemetry(None); + Ok(TryNextBatch::End) + } + Err(error) => { + self.finalize_telemetry(Some(&error)); + Err(error) + } + } + } + /// Non-consuming peek at the **first** batch of the stream. /// /// Pulls one batch from the reader exactly once and buffers it so a diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 5858af5f..025db78e 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -151,6 +151,33 @@ impl ExecutedStatement { Ok(None) } + /// Non-blocking counterpart to [`Self::next_batch`]. It preserves the same + /// drain-driven auto-close behavior when end-of-stream is observed. + pub fn try_next_batch(&mut self) -> Result> { + enum State { + Ready, + Pending, + End, + } + let state = match self.result_stream.try_next_batch()? { + crate::result_stream::TryNextBatch::Ready(_) => State::Ready, + crate::result_stream::TryNextBatch::Pending => State::Pending, + crate::result_stream::TryNextBatch::End => State::End, + }; + match state { + State::Ready => Ok(crate::result_stream::TryNextBatch::Ready( + self.result_stream + .current() + .expect("ready batch was just installed"), + )), + State::Pending => Ok(crate::result_stream::TryNextBatch::Pending), + State::End => { + self.spawn_close_if_open(); + Ok(crate::result_stream::TryNextBatch::End) + } + } + } + /// Explicit close for concrete sync statements. /// /// This finalizes result-stream telemetry before the server-side diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index aa3b45b7..9bff47ec 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -50,7 +50,9 @@ use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; -use databricks_sql_kernel::c_abi::result::{kernel_result_stream_close, kernel_result_stream_t}; +use databricks_sql_kernel::c_abi::result::{ + kernel_result_stream_close, kernel_result_stream_t, kernel_result_stream_try_next_batch, +}; 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_new_statement, kernel_session_open, @@ -63,13 +65,13 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_executed_async_statement_get_result_stream, kernel_executed_async_statement_num_modified_rows, kernel_executed_async_statement_query_id, kernel_executed_async_statement_status, kernel_executed_async_statement_t, - kernel_executed_statement_close, kernel_executed_statement_query_id, - kernel_executed_statement_t, kernel_statement_bind_parameter, - kernel_statement_canceller_cancel, kernel_statement_canceller_free, - kernel_statement_canceller_new, kernel_statement_canceller_t, kernel_statement_close, - kernel_statement_execute, kernel_statement_execute_with_timeout_ms, kernel_statement_set_sql, - kernel_statement_submit, kernel_statement_submit_with_timeout_ms, kernel_statement_t, - KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, + kernel_executed_statement_close, kernel_executed_statement_get_result_stream, + kernel_executed_statement_query_id, kernel_executed_statement_t, + kernel_statement_bind_parameter, kernel_statement_canceller_cancel, + kernel_statement_canceller_free, kernel_statement_canceller_new, kernel_statement_canceller_t, + kernel_statement_close, kernel_statement_execute, kernel_statement_execute_with_timeout_ms, + kernel_statement_set_sql, kernel_statement_submit, kernel_statement_submit_with_timeout_ms, + kernel_statement_t, KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, }; use databricks_sql_kernel::c_abi::KernelStatusCode; use serde_json::json; @@ -1364,6 +1366,106 @@ fn query_id_is_null_after_reexecute_invalidates_the_handle() { } } +#[test] +fn try_next_batch_on_stream_of_closed_executed_handle_returns_invalid_handle() { + // The C ABI `ResultStreamShape::Executed` arm routes `try_next_batch` + // through `executed_ref`, whose `alive` guard fires BEFORE the backing + // `ExecutedStatement` pointer is dereferenced. Closing the executed handle + // (`kernel_executed_statement_close`) invalidates that shared flag and frees + // the handle, so a subsequent `kernel_result_stream_try_next_batch` on a + // stream borrowed from it must yield `InvalidStatementHandle` — a defined + // error, never a use-after-free. This pins the Executed arm's stale-handle + // guard on the non-blocking path specifically (the blocking `next_batch` + // path shares the same guard, but nothing else exercises `try_next_batch` + // over an invalidated Executed stream). + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + // A terminal SUCCEEDED inline result: execute returns a live executed + // handle we can borrow a stream from. + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-stale")), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + 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 1").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 + ); + + // Borrow a result stream from the live executed handle. + 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()); + + // Close (and free) the executed handle. This invalidates the shared + // `alive` flag the borrowed stream checks. + assert_eq!( + kernel_executed_statement_close(exec), + KernelStatusCode::Success + ); + + // The stream is now stale: try_next_batch must surface + // InvalidStatementHandle via the Executed arm's `executed_ref` guard, + // not dereference the freed handle. + let mut ready = true; + let mut arr = arrow_array::ffi::FFI_ArrowArray::empty(); + let mut sch = arrow_array::ffi::FFI_ArrowSchema::empty(); + let rc = kernel_result_stream_try_next_batch(stream, &mut ready, &mut arr, &mut sch); + assert_eq!( + rc, + KernelStatusCode::InvalidStatementHandle, + "try_next_batch on a stream of a closed executed handle must return \ + InvalidStatementHandle" + ); + assert!(!ready, "no batch may be reported ready on a stale handle"); + + // The typed error is retrievable on the caller thread. + let mut err = std::mem::MaybeUninit::::uninit(); + assert!( + kernel_get_last_error(err.as_mut_ptr()), + "a typed error must accompany the stale-handle rejection" + ); + assert_eq!( + err.assume_init().code, + KernelStatusCode::InvalidStatementHandle as i32, + ); + + // Orderly teardown: close the (stale) stream, then statement + session. + assert_eq!( + kernel_result_stream_close(stream), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + #[test] fn bind_parameter_null_and_empty_sql_type_are_rejected_at_bind() { // The bridge validates sql_type before pushing: NULL type and empty type both diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 218577bc..e16360ee 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -32,8 +32,8 @@ use arrow_schema::{DataType, Field, Fields, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, - GeospatialResultRepresentation, HttpConfig, ResultBatch, ResultConfig, Session, TypedValue, - MAX_CLIENT_QUERY_TIMEOUT, + GeospatialResultRepresentation, HttpConfig, ResultBatch, ResultConfig, Session, TryNextBatch, + TypedValue, MAX_CLIENT_QUERY_TIMEOUT, }; use serde_json::json; use std::collections::HashMap; @@ -2055,6 +2055,75 @@ async fn execute_succeeded_inline_still_closes_statement() { // `_close` also verifies expect(1) when it drops at end of scope. } +/// The non-blocking `ExecutedStatement::try_next_batch` must preserve the same +/// drain-driven auto-close as the blocking `next_batch`: the first time it +/// observes `TryNextBatch::End` it fires exactly one fire-and-forget +/// `CloseStatement` (DELETE) on a `SUCCEEDED` (server-owned) statement. This +/// pins the `State::End => { self.spawn_close_if_open(); ... }` arm, which the +/// doc comment claims "preserves the same drain-driven auto-close behavior" — +/// a claim otherwise covered only on the blocking sibling. +#[tokio::test] +async fn try_next_batch_drain_auto_closes_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let batch = int64_batch("n", vec![1]); + // SUCCEEDED (not CLOSED): the server still owns the statement, so draining + // to End must trigger exactly one CloseStatement. + mount_execute(&server, succeeded_inline_body("stmt-try-drain", &batch)).await; + + let _close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-try-drain")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount_as_scoped(&server) + .await; + + let session = open_session(&server).await; + { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await.expect("execute"); + + // Drain via the non-blocking API. The inline direct-result payload is + // already buffered, so try_next_batch never has to report Pending here; + // a defensive bound keeps a regression from spinning forever. + let mut saw_ready = false; + let mut saw_end = false; + for _ in 0..1000 { + match exec.try_next_batch().expect("try_next_batch") { + TryNextBatch::Ready(_) => saw_ready = true, + TryNextBatch::Pending => { + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + TryNextBatch::End => { + saw_end = true; + break; + } + _ => unreachable!("TryNextBatch has only Ready/Pending/End today"), + } + } + assert!(saw_ready, "the one buffered batch must surface as Ready"); + assert!(saw_end, "draining must reach End"); + // No explicit close(): the End-arm auto-close is the only path that can + // fire the DELETE below. exec/stmt drop at end of scope. + } + + let closes = wait_for_close_delete( + &server, + "stmt-try-drain", + 1, + std::time::Duration::from_millis(2000), + ) + .await; + assert_eq!( + closes, 1, + "try_next_batch draining to End must trigger exactly one CloseStatement" + ); + // `_close` also verifies expect(1) when it drops at end of scope. +} + // ─── Client query timeout ─────────────────────────────────────────── #[tokio::test]