diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..91e3319e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- `ResultStream::try_next_ready_batch()` advances the stream when a batch is ready without blocking. Errors and end-of-stream remain deferred until a normal fetch observes them. + ### Changed ### Updated diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..81bc6f0f 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -16,6 +16,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Changed +- Result fetches pack already-buffered Arrow batches into IPC payloads capped at 16,384 rows, 1MiB of sliced Arrow data (excluding IPC framing), and 16 messages, without waiting for another download. Single oversized batches and schemas containing dictionaries retain one batch per payload. + ### Updated ### Fixed diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..661172f2 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -721,13 +721,13 @@ export interface RawParameterInput { value?: string } /** - * A single Arrow IPC stream payload encoding one record batch (plus + * A single Arrow IPC stream payload encoding one or more record batches (plus * the schema header so the JS-side reader is stateless). */ export interface ArrowBatch { /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. + * Arrow IPC stream payload (schema header + record-batch messages). + * Decode with `apache-arrow`'s `RecordBatchReader`. */ ipcBytes: Buffer } @@ -887,10 +887,10 @@ export declare class AsyncResultHandle { /** * Pull the next batch of results. Returns `null` when the * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. + * complete Arrow IPC stream (schema header + one or more record-batch + * messages), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Uses the same bounded packing as + * `Statement.fetchNextBatch()`. * Rejects with `KernelError(InvalidStatementHandle)` after the * parent `AsyncStatement` is closed (see `AsyncStatement.close()`). */ @@ -1225,7 +1225,7 @@ export declare class Statement { /** * Pull the next batch of results. Returns `null` when the stream * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) + * Arrow IPC stream (schema header + one or more record-batch messages) * suitable for handing to `apache-arrow`'s `RecordBatchReader`. * * On `Err`, the stream is in an unspecified state — call diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index df416254..0d2e9c7f 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -60,11 +60,11 @@ use tokio::sync::Mutex; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ AsyncStatementCanceller, Error as KernelError, ExecutedAsyncStatement, ExecutedStatementHandle, - ResultBatch, ResultStream, Statement as KernelStatement, + ResultStream, Statement as KernelStatement, }; use crate::error::napi_err_from_kernel; -use crate::result::{encode_ipc_stream, ArrowBatch, ArrowSchema}; +use crate::result::{encode_ipc_stream, ArrowBatch, ArrowSchema, IpcStream}; use crate::runtime; use crate::util::guarded; @@ -89,7 +89,7 @@ fn closed_err(what: &str) -> napi::Error { // ───────────────────────── AsyncStatement ───────────────────────── /// An `AsyncResultHandle`'s stream, shared with its parent `AsyncStatement`. -type ResultSlot = Mutex>; +type ResultSlot = Mutex>>; /// Inner state for the JS-visible `AsyncStatement` wrapper. Same /// shape rationale as `StatementInner` in `statement.rs`: we hold @@ -320,7 +320,7 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); - let stream = Arc::new(Mutex::new(Some(stream))); + let stream = Arc::new(Mutex::new(Some(IpcStream::new(stream)))); // Registered while `inner` is held, so a queued `close()` sees it. results .lock() @@ -473,10 +473,10 @@ impl AsyncResultHandle { /// Pull the next batch of results. Returns `null` when the /// stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - /// complete Arrow IPC stream (schema header + 1 record-batch - /// message), suitable for handing to `apache-arrow`'s - /// `RecordBatchReader`. Byte-identical to the sync - /// `Statement.fetchNextBatch()` payload for the same query. + /// complete Arrow IPC stream (schema header + one or more record-batch + /// messages), suitable for handing to `apache-arrow`'s + /// `RecordBatchReader`. Uses the same bounded packing as + /// `Statement.fetchNextBatch()`. /// Rejects with `KernelError(InvalidStatementHandle)` after the /// parent `AsyncStatement` is closed (see `AsyncStatement.close()`). #[napi] @@ -488,24 +488,10 @@ impl AsyncResultHandle { let stream = guard .as_mut() .ok_or_else(|| closed_err("AsyncResultHandle"))?; - let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; - let Some(batch) = maybe_batch else { + let maybe_bytes = stream.next(&schema, "databricks-sea-native").await?; + let Some(bytes) = maybe_bytes else { return Ok(None); }; - let record_batch = match batch { - ResultBatch::Arrow(rb) => rb, - _ => { - return Err(napi_err_from_kernel( - KernelError::invalid_argument().message(format!( - "non-Arrow ResultBatch variant from kernel — \ - databricks-sea-native v{} cannot decode this batch \ - shape, upgrade the binding", - env!("CARGO_PKG_VERSION"), - )), - )); - } - }; - let bytes = encode_ipc_stream(&schema, Some(record_batch))?; Ok(Some(ArrowBatch { ipc_bytes: bytes.into(), })) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 7aba91ff..e29542ac 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -702,6 +702,243 @@ mod tests { assert_eq!(conn.session_id(), "session-survives-close"); } + async fn packed_statement_observations(server: &MockServer) -> (usize, Vec) { + let requests = server.received_requests().await.unwrap(); + let closes = requests + .iter() + .filter(|request| { + request.method.as_str() == "DELETE" + && request.url.path() == "/api/2.0/sql/statements/stmt-packed-eof" + }) + .count(); + let events = requests + .iter() + .filter(|request| request.url.path() == "/telemetry-ext") + .flat_map(|request| { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap(); + body["protoLogs"] + .as_array() + .unwrap() + .iter() + .map(|log| { + serde_json::from_str::(log.as_str().unwrap()).unwrap() + }) + .filter(|log| { + log["entry"]["sql_driver_log"]["sql_statement_id"] == "stmt-packed-eof" + }) + .collect::>() + }) + .collect(); + (closes, events) + } + + #[tokio::test] + async fn packed_executed_path_defers_close_and_telemetry_until_consumed() { + use arrow_array::{ArrayRef, Int64Array, RecordBatch}; + use arrow_ipc::{reader::StreamReader, writer::StreamWriter}; + use databricks_sql_kernel::TelemetryConfig; + use std::time::Duration; + + for (early_close, failed_download) in [(false, false), (true, false), (false, true)] { + let server = MockServer::start().await; + let batch = RecordBatch::try_from_iter([( + "n", + Arc::new(Int64Array::from(vec![Some(13), None, Some(-7)])) as ArrayRef, + )]) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + for _ in 0..3 { + writer.write(&batch).unwrap(); + } + writer.finish().unwrap(); + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "session_id": "sess-packed-eof" + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/chunk")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc.clone())) + .expect(1) + .mount(&server) + .await; + if failed_download { + Mock::given(method("GET")) + .and(path("/failed-chunk")) + .respond_with( + ResponseTemplate::new(500).set_body_string("fixture download failure"), + ) + .expect(5) + .mount(&server) + .await; + } + let mut links = vec![json!({ + "external_link": format!("{}/chunk", server.uri()), + "expiration": "2099-01-01T00:00:00Z", + "chunk_index": 0, "row_offset": 0, "row_count": 9, "byte_count": ipc.len() + })]; + if failed_download { + links.push(json!({ + "external_link": format!("{}/failed-chunk", server.uri()), + "expiration": "2099-01-01T00:00:00Z", + "chunk_index": 1, "row_offset": 9, "row_count": 3, "byte_count": ipc.len() + })); + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "stmt-packed-eof", + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { "column_count": 1, "columns": [{ + "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 + }] }, + "total_chunk_count": links.len(), "total_row_count": if failed_download { 12 } else { 9 }, + "total_byte_count": ipc.len(), "truncated": false + }, + "result": { "external_links": links } + }))) + .mount(&server) + .await; + for endpoint in [ + "/api/2.0/sql/statements/stmt-packed-eof", + "/api/2.0/sql/sessions/sess-packed-eof", + ] { + Mock::given(method("DELETE")) + .and(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .expect(1) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path("/telemetry-ext")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .mount(&server) + .await; + let mut telemetry = TelemetryConfig::default(); + telemetry.set_enabled(true); + telemetry.batch_size = 1; + telemetry.flush_interval = Duration::from_millis(10); + let mut http = databricks_sql_kernel::HttpConfig::default(); + http.retry_max_retries = 0; + let session = Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .telemetry(telemetry) + .http(http) + .open() + .await + .unwrap(); + let connection = Connection { + session_id: session.session_id().to_owned(), + inner: Arc::new(Mutex::new(Some(session))), + }; + let statement = connection + .execute_statement("SELECT n".into(), None) + .await + .unwrap(); + let payload = statement.fetch_next_batch().await.unwrap().unwrap(); + let batches: Vec<_> = StreamReader::try_new(payload.ipc_bytes.as_ref(), None) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(batches.len(), 3); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 9); + for actual in &batches { + assert_eq!( + actual + .column(0) + .as_any() + .downcast_ref::() + .unwrap(), + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + ); + } + // The fetch mutex is the completion barrier. Inspect synchronous EOF + // state so a queued-but-not-yet-sent DELETE cannot hide an early close. + assert!(statement.has_current_batch_for_test().await); + let (closes, events) = packed_statement_observations(&server).await; + assert_eq!(closes, 0, "lookahead must not close before the null fetch"); + assert!( + events.is_empty(), + "lookahead must not finalize statement telemetry" + ); + + let mut delivered_error_code = None; + if failed_download { + let error = + tokio::time::timeout(Duration::from_secs(15), statement.fetch_next_batch()) + .await + .expect("bounded retry failure") + .err() + .expect("second fetch must deliver the failed download"); + assert!( + error.reason.contains("NetworkError") || error.reason.contains("Internal"), + "{}", + error.reason + ); + let envelope: serde_json::Value = serde_json::from_str( + error + .reason + .strip_prefix(crate::error::ERROR_SENTINEL) + .unwrap(), + ) + .unwrap(); + delivered_error_code = Some(envelope["code"].as_str().unwrap().to_owned()); + assert_eq!( + packed_statement_observations(&server).await.0, + 0, + "a delivered download error must not auto-close" + ); + statement.close().await.unwrap(); + } else if early_close { + statement.close().await.unwrap(); + } else { + assert!(statement.fetch_next_batch().await.unwrap().is_none()); + } + let completed = tokio::time::timeout(Duration::from_secs(2), async { + loop { + let (closes, events) = packed_statement_observations(&server).await; + if closes == 1 && events.len() == 1 { + let latency = &events[0]["entry"]["sql_driver_log"]["sql_operation"] + ["result_latency"]["result_set_consumption_latency_millis"]; + assert_eq!(latency.is_null(), early_close); + let error_name = + &events[0]["entry"]["sql_driver_log"]["error_info"]["error_name"]; + assert_eq!(error_name.as_str(), delivered_error_code.as_deref()); + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await; + assert!( + completed.is_ok(), + "completion early_close={early_close} failed_download={failed_download}: {:?}", + packed_statement_observations(&server).await + ); + statement.close().await.unwrap(); + connection.close().await.unwrap(); + let (closes, events) = packed_statement_observations(&server).await; + assert_eq!(closes, 1); + assert_eq!(events.len(), 1, "close must not duplicate error telemetry"); + } + } + #[tokio::test] async fn build_statement_forwards_raw_params_and_rejects_mixed_binding() { let server = MockServer::start().await; diff --git a/napi/src/result.rs b/napi/src/result.rs index 2573bb84..d227aee8 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -17,22 +17,26 @@ //! Per sea-design.md Layer 2: "The binding ships the batch across the //! FFI as Arrow IPC bytes. The adapter converts those bytes into //! JavaScript rows…" — so the napi boundary is intentionally narrow: -//! one envelope per batch, one envelope per schema. +//! one envelope per bounded group of ready batches, one per schema. use arrow_array::RecordBatch; use arrow_ipc::writer::StreamWriter; -use arrow_schema::SchemaRef; -use databricks_sql_kernel::Error as KernelError; +use arrow_schema::{DataType, SchemaRef}; +use databricks_sql_kernel::{ + result_stream::TryNextBatch, Error as KernelError, ResultBatch, ResultStream, +}; use napi::bindgen_prelude::Buffer; use crate::error::napi_err_from_kernel; -/// A single Arrow IPC stream payload encoding one record batch (plus +const IPC_TARGET_BYTES: usize = 1024 * 1024; + +/// A single Arrow IPC stream payload encoding one or more record batches (plus /// the schema header so the JS-side reader is stateless). #[napi(object)] pub struct ArrowBatch { - /// Arrow IPC stream payload (schema header + 1 record-batch - /// message). Decode with `apache-arrow`'s `RecordBatchReader`. + /// Arrow IPC stream payload (schema header + record-batch messages). + /// Decode with `apache-arrow`'s `RecordBatchReader`. pub ipc_bytes: Buffer, } @@ -49,44 +53,38 @@ pub struct ArrowSchema { /// Encode an Arrow schema (and an optional single record batch) as a /// complete, self-contained Arrow IPC stream payload. /// -/// Shared single source of truth for every batch/schema that crosses -/// the napi boundary: the sync `Statement` path (`schema()` / -/// `fetchNextBatch()` in `statement.rs`) and the async -/// `AsyncResultHandle` path (`async_statement.rs`) both call this, so -/// the two emit byte-identical envelopes and route encode failures -/// through the same kernel error envelope (`napi_err_from_kernel`) — -/// the TS reviver sees a typed `KernelError(code='Internal')` rather -/// than a bare `GenericFailure` string. Lives here in `result.rs` -/// because this module already owns `ArrowBatch` / `ArrowSchema`, the -/// payload types these bytes are wrapped in. -/// -/// Returning a self-contained IPC stream per call is wasteful -/// header-wise but lets the JS adapter stay stateless — it decodes -/// each `ipcBytes` independently via the same `apache-arrow` -/// `RecordBatchReader` path. +/// Schema getters and `IpcStream` share the same writer and typed error +/// envelope. Each payload stays self-contained for stateless JS readers; +/// fetch paths amortize the schema header across ready record batches. pub(crate) fn encode_ipc_stream( schema: &SchemaRef, batch: Option<&RecordBatch>, ) -> napi::Result> { + encode_ipc_batches(schema, batch.map(std::slice::from_ref).unwrap_or_default()) +} + +fn encode_ipc_batches(schema: &SchemaRef, batches: &[RecordBatch]) -> napi::Result> { fn encode_err(stage: &str, e: impl std::fmt::Display) -> napi::Error { napi_err_from_kernel( KernelError::internal().message(format!("Arrow IPC writer {stage} failed: {e}")), ) } - // Pre-size the buffer so a typical 500KB batch doesn't reallocate - // ~17 times growing from `Vec::new()`'s default capacity of 0. - // `get_array_memory_size` is the kernel-side memory footprint (close - // enough to the IPC-encoded size for capacity-hint purposes — IPC - // adds ~hundreds of bytes of framing per batch, not orders of - // magnitude). 4 KiB slack covers the schema-header on the - // schema-only path (`batch = None`) and the framing overhead on - // the schema+batch path. - let estimated = batch.map(|rb| rb.get_array_memory_size()).unwrap_or(0) + 4096; + // IPC-decoded arrays can share a much larger backing buffer. Reserve for + // the slices being encoded, with slack for schema and message framing. + // Unsupported sizing falls back to the writer's normal buffer growth. + let estimated = batches + .iter() + .map(sliced_batch_bytes) + .filter(|&bytes| bytes != usize::MAX) + .fold( + 4096usize.saturating_add(batches.len().saturating_mul(1024)), + usize::saturating_add, + ); let mut buf: Vec = Vec::with_capacity(estimated); { let mut writer = StreamWriter::try_new(&mut buf, schema).map_err(|e| encode_err("init", e))?; - if let Some(rb) = batch { + for rb in batches { writer.write(rb).map_err(|e| encode_err("write", e))?; } writer.finish().map_err(|e| encode_err("finish", e))?; @@ -94,6 +92,137 @@ pub(crate) fn encode_ipc_stream( Ok(buf) } +fn sliced_batch_bytes(batch: &RecordBatch) -> usize { + batch + .columns() + .iter() + .try_fold(0usize, |bytes, array| { + bytes.checked_add(array.to_data().get_slice_memory_size().ok()?) + }) + .unwrap_or(usize::MAX) +} + +fn contains_dictionary(data_type: &DataType) -> bool { + match data_type { + DataType::Dictionary(_, _) => true, + DataType::List(field) + | DataType::LargeList(field) + | DataType::ListView(field) + | DataType::LargeListView(field) + | DataType::FixedSizeList(field, _) + | DataType::Map(field, _) => contains_dictionary(field.data_type()), + DataType::Struct(fields) => fields + .iter() + .any(|field| contains_dictionary(field.data_type())), + DataType::Union(fields, _) => fields + .iter() + .any(|(_, field)| contains_dictionary(field.data_type())), + DataType::RunEndEncoded(ends, values) => { + contains_dictionary(ends.data_type()) || contains_dictionary(values.data_type()) + } + _ => false, + } +} + +pub(crate) trait BatchSource: Send { + fn next_batch( + &mut self, + ) -> impl std::future::Future>> + Send; + + fn try_next_ready_batch(&mut self) -> databricks_sql_kernel::Result>; +} + +impl BatchSource for ResultStream { + async fn next_batch(&mut self) -> databricks_sql_kernel::Result> { + ResultStream::next_batch(self).await + } + + fn try_next_ready_batch(&mut self) -> databricks_sql_kernel::Result> { + ResultStream::try_next_ready_batch(self) + } +} + +pub(crate) struct IpcStream { + pub(crate) source: Source, + pending: Option>, + packing_allowed: Option, +} + +impl IpcStream { + pub(crate) fn new(source: Source) -> Self { + Self { + source, + pending: None, + packing_allowed: None, + } + } + + pub(crate) async fn next( + &mut self, + schema: &SchemaRef, + binding_name: &str, + ) -> napi::Result>> { + // apache-arrow 13 ignores dictionary replacements within a stream. + let packing_allowed = *self.packing_allowed.get_or_insert_with(|| { + !schema + .fields() + .iter() + .any(|field| contains_dictionary(field.data_type())) + }); + let first = match self.pending.take() { + Some(batch) => batch?, + None => { + let Some(batch) = self + .source + .next_batch() + .await + .map_err(napi_err_from_kernel)? + else { + return Ok(None); + }; + clone_arrow_batch(batch, binding_name)? + } + }; + let mut rows = first.num_rows(); + let mut bytes = sliced_batch_bytes(&first); + let mut batches = vec![first]; + while packing_allowed && rows < 16_384 && bytes < IPC_TARGET_BYTES && batches.len() < 16 { + let candidate = match self.source.try_next_ready_batch() { + Ok(TryNextBatch::Ready(batch)) => clone_arrow_batch(batch, binding_name), + Ok(TryNextBatch::Pending | TryNextBatch::End) => break, + Err(error) => Err(napi_err_from_kernel(error)), + Ok(_) => break, + }; + let candidate = match candidate { + Ok(batch) => batch, + Err(error) => { + self.pending = Some(Err(error)); + break; + } + }; + let candidate_bytes = sliced_batch_bytes(&candidate); + if candidate.num_rows() > 16_384 - rows || candidate_bytes > IPC_TARGET_BYTES - bytes { + self.pending = Some(Ok(candidate)); + break; + } + rows += candidate.num_rows(); + bytes += candidate_bytes; + batches.push(candidate); + } + encode_ipc_batches(schema, &batches).map(Some) + } +} + +fn clone_arrow_batch(batch: &ResultBatch, binding_name: &str) -> napi::Result { + match batch { + ResultBatch::Arrow(batch) => Ok(batch.clone()), + _ => Err(napi_err_from_kernel(KernelError::invalid_argument().message(format!( + "non-Arrow ResultBatch variant from kernel — {binding_name} v{} cannot decode this batch shape, upgrade the binding", + env!("CARGO_PKG_VERSION"), + )))), + } +} + #[cfg(test)] mod tests { use super::*; @@ -136,4 +265,449 @@ mod tests { assert_eq!(decoded[0].num_rows(), 3); assert_eq!(decoded[0].schema().fields(), schema.fields()); } + + #[test] + fn oversized_owned_batch_does_not_retain_a_doubled_output_buffer() { + use arrow_array::StringArray; + let batch = RecordBatch::try_from_iter([( + "value", + Arc::new(StringArray::from(vec![Some("x".repeat(1536 * 1024)), None])) + as arrow_array::ArrayRef, + )]) + .unwrap(); + let bytes = encode_ipc_stream(&batch.schema(), Some(&batch)).unwrap(); + assert!(bytes.len() > IPC_TARGET_BYTES); + assert!(bytes.capacity() < bytes.len() * 11 / 10); + assert_eq!(decode(bytes), vec![batch]); + } + + #[test] + fn message_framing_does_not_double_the_output_buffer() { + use arrow_array::{ArrayRef, Int64Array}; + let batch = RecordBatch::try_from_iter((0..16).map(|column| { + ( + format!("column{column}"), + Arc::new(Int64Array::from_iter( + (0..480).map(|row| (row % 11 != 0).then_some(row + column)), + )) as ArrayRef, + ) + })) + .unwrap(); + let batches = vec![batch; 16]; + let bytes = encode_ipc_batches(&batches[0].schema(), &batches).unwrap(); + assert!(bytes.capacity() < bytes.len() * 11 / 10); + assert_eq!(decode(bytes), batches); + } + + struct Source { + items: std::collections::VecDeque>>, + current: Option, + awaits: usize, + probes: usize, + deferred_error: Option, + } + + impl Source { + fn new(batches: Vec) -> Self { + Self { + items: batches.into_iter().map(|batch| Ok(Some(batch))).collect(), + current: None, + awaits: 0, + probes: 0, + deferred_error: None, + } + } + + fn take(&mut self, speculative: bool) -> databricks_sql_kernel::Result> { + if self.deferred_error.is_some() { + if speculative { + return Ok(TryNextBatch::Pending); + } + return Err(self.deferred_error.take().unwrap()); + } + match self.items.pop_front() { + Some(Ok(Some(batch))) => { + self.current = Some(ResultBatch::Arrow(batch)); + Ok(TryNextBatch::Ready(self.current.as_ref().unwrap())) + } + Some(Ok(None)) => Ok(TryNextBatch::Pending), + Some(Err(error)) if speculative => { + self.deferred_error = Some(error); + Ok(TryNextBatch::Pending) + } + Some(Err(error)) => Err(error), + None => Ok(TryNextBatch::End), + } + } + } + + impl BatchSource for Source { + async fn next_batch(&mut self) -> databricks_sql_kernel::Result> { + self.awaits += 1; + match self.take(false)? { + TryNextBatch::Ready(batch) => Ok(Some(batch)), + TryNextBatch::End => Ok(None), + _ => panic!("packing must not await a pending batch"), + } + } + + fn try_next_ready_batch(&mut self) -> databricks_sql_kernel::Result> { + self.probes += 1; + self.take(true) + } + } + + fn int_batch(rows: usize, value: i32) -> RecordBatch { + RecordBatch::try_new( + make_schema(), + vec![Arc::new(Int32Array::from(vec![value; rows]))], + ) + .unwrap() + } + + fn decode(bytes: Vec) -> Vec { + StreamReader::try_new(bytes.as_slice(), None) + .unwrap() + .collect::>() + .unwrap() + } + + async fn next(stream: &mut IpcStream, schema: &SchemaRef) -> Vec { + decode(stream.next(schema, "test").await.unwrap().unwrap()) + } + + #[tokio::test] + async fn packing_stops_at_row_target_and_replays_lookahead() { + let first = int_batch(12_000, 1); + let second = int_batch(12_000, 2); + let mut stream = IpcStream::new(Source::new(vec![first.clone(), second.clone()])); + assert_eq!(next(&mut stream, &make_schema()).await, vec![first]); + assert_eq!(next(&mut stream, &make_schema()).await, vec![second]); + assert!(stream.next(&make_schema(), "test").await.unwrap().is_none()); + } + + #[tokio::test] + async fn packing_never_probes_past_full_or_oversized_first_batch() { + for rows in [16_384, 20_000] { + let batch = int_batch(rows, 9); + let mut stream = IpcStream::new(Source::new(vec![batch.clone(), int_batch(1, 2)])); + assert_eq!(next(&mut stream, &make_schema()).await, vec![batch]); + assert_eq!(stream.source.probes, 0); + assert_eq!( + next(&mut stream, &make_schema()).await, + vec![int_batch(1, 2)] + ); + } + } + + #[tokio::test] + async fn packing_byte_limit_defers_instead_of_dropping_large_batch() { + use arrow_array::StringArray; + let array = Arc::new(StringArray::from(vec![ + Some("x".repeat(IPC_TARGET_BYTES * 3 / 4)), + None, + ])); + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, true)])); + let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap(); + let mut stream = IpcStream::new(Source::new(vec![batch.clone(), batch.clone()])); + let first = next(&mut stream, &schema).await; + assert_eq!(first.len(), 1); + assert!(first[0] == batch); + let second = next(&mut stream, &schema).await; + assert_eq!(second.len(), 1); + assert!(second[0] == batch); + assert!(stream.next(&schema, "test").await.unwrap().is_none()); + } + + #[tokio::test] + async fn oversized_byte_batch_does_not_probe() { + use arrow_array::StringArray; + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, true)])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(StringArray::from(vec![ + "x".repeat(5 * 1024 * 1024) + ]))], + ) + .unwrap(); + let mut stream = IpcStream::new(Source::new(vec![batch.clone(), batch.clone()])); + assert!(next(&mut stream, &schema).await == vec![batch]); + assert_eq!(stream.source.probes, 0); + } + + #[tokio::test] + async fn empty_batches_are_preserved_and_batch_count_is_bounded() { + let batches = vec![int_batch(0, 0); 32]; + let mut stream = IpcStream::new(Source::new(batches)); + assert_eq!(next(&mut stream, &make_schema()).await.len(), 16); + assert_eq!(next(&mut stream, &make_schema()).await.len(), 16); + assert!(stream.next(&make_schema(), "test").await.unwrap().is_none()); + assert_eq!(stream.source.awaits, 3); + } + + #[tokio::test] + async fn pending_batch_returns_without_another_await() { + let mut source = Source::new(vec![int_batch(1, 1)]); + source.items.extend([Ok(None), Ok(Some(int_batch(1, 2)))]); + let mut stream = IpcStream::new(source); + assert_eq!( + next(&mut stream, &make_schema()).await, + vec![int_batch(1, 1)] + ); + assert_eq!(stream.source.awaits, 1); + assert_eq!( + next(&mut stream, &make_schema()).await, + vec![int_batch(1, 2)] + ); + } + + #[tokio::test] + async fn lookahead_error_is_replayed_after_already_available_rows() { + let mut source = Source::new(vec![int_batch(1, 1)]); + source + .items + .push_back(Err(KernelError::io().message("late download error"))); + let mut stream = IpcStream::new(source); + assert_eq!( + next(&mut stream, &make_schema()).await, + vec![int_batch(1, 1)] + ); + let error = stream.next(&make_schema(), "test").await.unwrap_err(); + assert!(error.reason.contains("late download error")); + assert_eq!(stream.source.awaits, 2); + } + + #[tokio::test] + async fn full_group_round_trips_without_array_concatenation() { + let batch = int_batch(4096, 13); + let mut stream = IpcStream::new(Source::new(vec![batch.clone(); 5])); + assert_eq!( + next(&mut stream, &make_schema()).await, + vec![batch.clone(); 4] + ); + assert_eq!(stream.source.probes, 3); + assert_eq!(next(&mut stream, &make_schema()).await, vec![batch]); + } + + #[tokio::test] + async fn decoded_wide_slices_share_backing_memory_without_inflating_budget() { + use arrow_array::{ArrayRef, Int64Array}; + let batch = RecordBatch::try_from_iter((0..8).map(|column| { + ( + format!("column{column}"), + Arc::new(Int64Array::from_iter( + (0..2840).map(|row| (row % 11 != 0).then_some(row + column)), + )) as ArrayRef, + ) + })) + .unwrap(); + let bytes = encode_ipc_batches(&batch.schema(), &[batch]).unwrap(); + let decoded = + StreamReader::try_new(std::io::BufReader::new(std::io::Cursor::new(bytes)), None) + .unwrap() + .next() + .unwrap() + .unwrap(); + assert!(decoded.get_array_memory_size() > IPC_TARGET_BYTES); + assert!(sliced_batch_bytes(&decoded) < 200_000); + let schema = decoded.schema(); + let mut stream = IpcStream::new(Source::new(vec![decoded.clone(); 6])); + let bytes = stream.next(&schema, "test").await.unwrap().unwrap(); + assert!(bytes.len() < IPC_TARGET_BYTES); + assert_eq!(decode(bytes), vec![decoded.clone(); 5]); + assert_eq!(next(&mut stream, &schema).await, vec![decoded]); + } + + #[tokio::test] + async fn nullable_arrow_types_and_metadata_round_trip_across_messages() { + use arrow_array::builder::{Int32Builder, MapBuilder, StringBuilder}; + use arrow_array::*; + let mut map = MapBuilder::new(None, StringBuilder::new(), Int32Builder::new()); + map.keys().append_value("key"); + map.values().append_null(); + map.append(true).unwrap(); + map.append(false).unwrap(); + let structure = StructArray::from(vec![( + Arc::new(Field::new("nested", DataType::Utf8, true)), + Arc::new(StringArray::from(vec![Some("value"), None])) as ArrayRef, + )]); + let arrays: Vec = vec![ + Arc::new(BooleanArray::from(vec![Some(true), None])), + Arc::new(Int8Array::from(vec![Some(-1), None])), + Arc::new(Int16Array::from(vec![Some(-300), None])), + Arc::new(Int32Array::from(vec![Some(-70_000), None])), + Arc::new(Int64Array::from(vec![Some(9_007_199_254_740_993), None])), + Arc::new(UInt64Array::from(vec![Some(u64::MAX), None])), + Arc::new(Float32Array::from(vec![Some(1.25), None])), + Arc::new(Float64Array::from(vec![Some(-0.0), None])), + Arc::new(StringArray::from(vec![Some("héllo"), None])), + Arc::new(LargeStringArray::from(vec![Some("world"), None])), + Arc::new(BinaryArray::from(vec![Some(b"\x00\xff".as_slice()), None])), + Arc::new( + Decimal128Array::from(vec![Some(12345), None]) + .with_precision_and_scale(20, 3) + .unwrap(), + ), + Arc::new(Date32Array::from(vec![Some(-1), None])), + Arc::new( + TimestampMicrosecondArray::from(vec![Some(1_234_567), None]).with_timezone("UTC"), + ), + Arc::new(TimestampMicrosecondArray::from(vec![ + Some(-1_234_567), + None, + ])), + Arc::new(DurationSecondArray::from(vec![Some(-1), None])), + Arc::new(DurationMillisecondArray::from(vec![Some(-1001), None])), + Arc::new(DurationMicrosecondArray::from(vec![Some(1_000_001), None])), + Arc::new(DurationNanosecondArray::from(vec![ + Some(-1_000_000_001), + None, + ])), + Arc::new(IntervalYearMonthArray::from(vec![Some(15), None])), + Arc::new(IntervalDayTimeArray::from(vec![ + Some(types::IntervalDayTimeType::make_value(-1, 2)), + None, + ])), + Arc::new(IntervalMonthDayNanoArray::from(vec![ + Some(types::IntervalMonthDayNanoType::make_value(1, -2, 3)), + None, + ])), + Arc::new(ListArray::from_iter_primitive::([ + Some(vec![Some(1), None]), + None, + ])), + Arc::new(NullArray::new(2)), + Arc::new(map.finish()), + Arc::new(structure), + Arc::new( + Decimal256Array::from(vec![ + Some( + "123456789012345678901234567890123456789012" + .parse() + .unwrap(), + ), + None, + ]) + .with_precision_and_scale(50, 12) + .unwrap(), + ), + ]; + let fields = arrays + .iter() + .enumerate() + .map(|(index, array)| { + Field::new(format!("col{index}"), array.data_type().clone(), true).with_metadata( + std::collections::HashMap::from([( + "databricks.type_name".into(), + format!("type{index}"), + )]), + ) + }) + .collect::>(); + let schema = Arc::new(Schema::new(fields)); + let batch = RecordBatch::try_new(schema.clone(), arrays).unwrap(); + let mut stream = IpcStream::new(Source::new(vec![batch.clone(); 3])); + assert_eq!(next(&mut stream, &schema).await, vec![batch; 3]); + } + + #[tokio::test] + async fn dictionary_schemas_never_probe_or_pack_batches() { + check_dictionary_payloads(None).await; + } + + #[tokio::test] + #[ignore = "Exports fixtures for the manual apache-arrow consumer check"] + async fn export_dictionary_consumer_fixtures() { + let directory = std::path::PathBuf::from( + std::env::var_os("DICT_FIXTURE_DIR").expect("set DICT_FIXTURE_DIR for fixture export"), + ); + check_dictionary_payloads(Some(&directory)).await; + } + + async fn check_dictionary_payloads(directory: Option<&std::path::Path>) { + use arrow_array::{types::Int8Type, ArrayRef, DictionaryArray, StructArray}; + for nested in [false, true] { + let batches = ["first", "second"].map(|value| { + let dictionary = + Arc::new(DictionaryArray::::from_iter([Some(value), None])) + as ArrayRef; + let array = if nested { + Arc::new(StructArray::from(vec![( + Arc::new(Field::new("nested", dictionary.data_type().clone(), true)), + dictionary, + )])) as ArrayRef + } else { + dictionary + }; + RecordBatch::try_from_iter([("dictionary", array)]).unwrap() + }); + let schema = batches[0].schema(); + let mut stream = IpcStream::new(Source::new(batches.to_vec())); + for index in 0..2 { + let bytes = stream.next(&schema, "test").await.unwrap().unwrap(); + if let Some(directory) = directory { + std::fs::create_dir_all(directory).unwrap(); + std::fs::write(directory.join(format!("{nested}-{index}.arrow")), &bytes) + .unwrap(); + } + assert_eq!( + decode(bytes).len(), + 1, + "dictionary payloads must be independent" + ); + assert_eq!( + stream.source.probes, 0, + "dictionary data must not be speculatively consumed" + ); + } + assert!(stream.next(&schema, "test").await.unwrap().is_none()); + } + } + + #[test] + fn dictionary_guard_covers_every_nested_container() { + use arrow_schema::{UnionFields, UnionMode}; + let field = Arc::new(Field::new( + "dictionary", + DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)), + true, + )); + let containers = vec![ + field.data_type().clone(), + DataType::List(field.clone()), + DataType::LargeList(field.clone()), + DataType::ListView(field.clone()), + DataType::LargeListView(field.clone()), + DataType::FixedSizeList(field.clone(), 2), + DataType::Map( + Arc::new(Field::new( + "entries", + DataType::Struct( + vec![ + Arc::new(Field::new("key", DataType::Utf8, false)), + field.clone(), + ] + .into(), + ), + false, + )), + false, + ), + DataType::Struct(vec![field.clone()].into()), + DataType::Union( + UnionFields::try_new([0], [field.clone()]).unwrap(), + UnionMode::Dense, + ), + DataType::RunEndEncoded(Arc::new(Field::new("ends", DataType::Int16, false)), field), + ]; + for data_type in containers { + assert!(contains_dictionary(&data_type), "{data_type}"); + let nested = + DataType::Struct(vec![Arc::new(Field::new("outer", data_type, true))].into()); + assert!(contains_dictionary(&nested)); + } + assert!(!contains_dictionary(&DataType::Struct( + vec![Arc::new(Field::new("plain", DataType::Utf8, true))].into() + ))); + } } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 40d682d2..e64d7588 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -40,7 +40,7 @@ use databricks_sql_kernel::{ }; use crate::error::napi_err_from_kernel; -use crate::result::{ArrowBatch, ArrowSchema}; +use crate::result::{ArrowBatch, ArrowSchema, BatchSource, IpcStream}; use crate::runtime; use crate::util::guarded; @@ -79,7 +79,19 @@ enum AnyInner { Metadata(ResultStream), } -impl AnyInner { +impl BatchSource for AnyInner { + fn try_next_ready_batch( + &mut self, + ) -> databricks_sql_kernel::Result> { + match self { + AnyInner::Executed(statement) => statement + .executed + .result_stream_mut() + .try_next_ready_batch(), + AnyInner::Metadata(stream) => stream.try_next_ready_batch(), + } + } + /// Pull the next batch, variant-aware so the executed path gets the /// kernel's **auto-close-on-drain** (fire-and-forget CloseStatement /// once the stream is exhausted, after all lazy CloudFetch link @@ -119,7 +131,7 @@ pub struct Statement { /// handle via the shared `ValidityFlag`); the `Metadata` variant /// wraps a bare `ResultStream` produced by `Metadata::list_*` / /// `primary_keys` / `foreign_keys` / `type_info` / `table_types`. - inner: Arc>>, + inner: Arc>>>, /// Schema captured at construction. Available even after `close()`. /// For the `Executed` variant this is the executed handle's /// schema; for the `Metadata` variant it's the result-stream's @@ -154,11 +166,11 @@ impl Statement { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); Self { - inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( - StatementInner { + inner: Arc::new(Mutex::new(Some(IpcStream::new(AnyInner::Executed( + Box::new(StatementInner { _parent: parent, executed, - }, + }), ))))), schema, statement_id, @@ -179,7 +191,7 @@ impl Statement { pub(crate) fn from_result_stream(stream: ResultStream) -> Self { let schema = stream.schema(); Self { - inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), + inner: Arc::new(Mutex::new(Some(IpcStream::new(AnyInner::Metadata(stream))))), schema, statement_id: String::new(), finished: Arc::new(AtomicBool::new(false)), @@ -223,7 +235,7 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - match inner_state { + match &inner_state.source { AnyInner::Executed(s) => Ok(s.executed.num_modified_rows()), AnyInner::Metadata(_) => Ok(None), } @@ -257,7 +269,7 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - match inner_state { + match &inner_state.source { AnyInner::Executed(s) => Ok(s.executed.display_message().map(str::to_owned)), AnyInner::Metadata(_) => Ok(None), } @@ -276,7 +288,7 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - match inner_state { + match &inner_state.source { AnyInner::Executed(s) => Ok(s.executed.diagnostic_info().map(str::to_owned)), AnyInner::Metadata(_) => Ok(None), } @@ -304,7 +316,7 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - match inner_state { + match &inner_state.source { AnyInner::Executed(s) => Ok(s.executed.error_details_json().map(str::to_owned)), AnyInner::Metadata(_) => Ok(None), } @@ -314,7 +326,7 @@ impl Statement { /// Pull the next batch of results. Returns `null` when the stream /// is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - /// Arrow IPC stream (schema header + 1 record-batch message) + /// Arrow IPC stream (schema header + one or more record-batch messages) /// suitable for handing to `apache-arrow`'s `RecordBatchReader`. /// /// On `Err`, the stream is in an unspecified state — call @@ -336,44 +348,15 @@ impl Statement { // Variant-aware: the executed path auto-closes the server // statement on drain; the metadata path uses its own // close-on-drop guard. (See `AnyInner::next_batch`.) - let maybe_batch = inner_state - .next_batch() - .await - .map_err(napi_err_from_kernel)?; - let Some(batch) = maybe_batch else { + let maybe_bytes = inner_state + .next(&schema, "databricks-sql-kernel-napi") + .await?; + let Some(bytes) = maybe_bytes else { // End of stream — record so a defensive cancel after // natural completion can short-circuit to Ok(()). finished.store(true, Ordering::Release); return Ok(None); }; - // `ResultBatch` is `#[non_exhaustive]`; v0 only ever - // yields `Arrow`. The error arm exists for forward - // compat — v1+ may add ColumnarThrift / JsonRows / etc., - // and we want the binding to surface that as a typed - // error rather than silently misbehaving. - let record_batch = match batch { - ResultBatch::Arrow(rb) => rb, - _ => { - // `InvalidArgument`, not `Internal`: this isn't a - // kernel bug (which would page oncall via the - // Internal-category dashboards) — it's "binding - // too old for the kernel it's linked against." - // The kernel has rolled a new ResultBatch variant - // that this binding's decode path doesn't know - // how to handle, and the JS-side adapter should - // surface this as a version-skew error to the - // user. Matches the sibling-binding convention. - return Err(napi_err_from_kernel( - KernelError::invalid_argument().message(format!( - "non-Arrow ResultBatch variant from kernel — \ - databricks-sql-kernel-napi v{} cannot decode this batch \ - shape, upgrade the binding", - env!("CARGO_PKG_VERSION"), - )), - )); - } - }; - let bytes = crate::result::encode_ipc_stream(&schema, Some(record_batch))?; Ok(Some(ArrowBatch { ipc_bytes: bytes.into(), })) @@ -436,7 +419,7 @@ impl Statement { return Ok(()); } let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - match inner_state { + match &inner_state.source { AnyInner::Executed(s) => s.executed.cancel().await.map_err(napi_err_from_kernel), // Metadata streams have no server-side cancel handle, so the // query keeps running server-side. Emit a breadcrumb so a @@ -485,7 +468,7 @@ impl Statement { let mut guard = inner.lock().await; guard.take() }; - match inner_state { + match inner_state.map(|stream| stream.source) { Some(AnyInner::Executed(mut s)) => { ExecutedStatement::close(&mut s.executed) .await @@ -548,6 +531,17 @@ pub(crate) fn statement_closed_err() -> napi::Error { ) } +#[cfg(test)] +impl Statement { + pub(crate) async fn has_current_batch_for_test(&self) -> bool { + let guard = self.inner.lock().await; + match &guard.as_ref().expect("statement open").source { + AnyInner::Executed(statement) => statement.executed.result_stream().current().is_some(), + AnyInner::Metadata(stream) => stream.current().is_some(), + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 2a755096..6c241d89 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -1231,6 +1231,12 @@ impl ResultReader for ThriftReshapingReader { } } + fn try_next_ready_batch(&mut self) -> Result { + self.upstream + .try_next_ready_batch()? + .map_ready(|batch| self.reshape_batch(batch)) + } + fn try_next_batch(&mut self) -> Result { self.upstream .try_next_batch()? @@ -1244,6 +1250,69 @@ mod tests { use arrow_array::cast::AsArray; use arrow_array::{BooleanArray, RecordBatch}; + #[tokio::test] + async fn ready_probe_reshapes_batches_and_forwards_pending_and_end() { + use crate::reader::{InMemoryReader, TryNextBatch}; + + struct PendingOnce(InMemoryReader, bool); + + #[async_trait::async_trait] + impl ResultReader for PendingOnce { + async fn schema(&self) -> Result { + self.0.schema().await + } + + async fn next_batch(&mut self) -> Result> { + self.0.next_batch().await + } + + fn try_next_batch(&mut self) -> Result { + panic!("ready-only probing must use the upstream ready-only method"); + } + + fn try_next_ready_batch(&mut self) -> Result { + if std::mem::take(&mut self.1) { + Ok(TryNextBatch::Pending) + } else { + self.0.try_next_ready_batch() + } + } + } + + let batch = RecordBatch::try_from_iter([( + "catalog", + Arc::new(StringArray::from(vec![Some("main"), None])) as ArrayRef, + )]) + .unwrap(); + let upstream = PendingOnce(InMemoryReader::new(batch.schema(), vec![batch]), true); + let mut reader = ThriftReshapingReader::new( + Box::new(upstream), + GET_CATALOGS_SCHEMA.clone(), + Box::new(reshape_catalogs), + ); + assert_eq!(reader.schema().await.unwrap(), GET_CATALOGS_SCHEMA.clone()); + assert!(matches!( + reader.try_next_ready_batch().unwrap(), + TryNextBatch::Pending + )); + let TryNextBatch::Ready(batch) = reader.try_next_ready_batch().unwrap() else { + panic!("the ready upstream batch must be reshaped"); + }; + assert_eq!(batch.schema(), GET_CATALOGS_SCHEMA.clone()); + assert_eq!( + batch + .column(0) + .as_string::() + .iter() + .collect::>(), + vec![Some("main"), None] + ); + assert!(matches!( + reader.try_next_ready_batch().unwrap(), + TryNextBatch::End + )); + } + // ─── is_object_not_found tests ───────────────────────────────── fn err(state: Option<&str>, message: &str) -> Error { diff --git a/src/reader/mod.rs b/src/reader/mod.rs index fd616540..6746c3c2 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -728,6 +728,13 @@ pub trait ResultReader: Send + Sync { Err(Error::invalid_state().message("reader does not support non-blocking batch reads")) } + /// Optional speculative probe used by bindings to pack ready batches. + /// Returning `Pending` opts out, leaving the next normal fetch to make + /// progress. Polling readers should override this alongside `try_next_batch`. + fn try_next_ready_batch(&mut self) -> Result { + Ok(TryNextBatch::Pending) + } + /// Optional reader-level metrics accumulated below `ResultStream`. /// /// CloudFetch overrides this to surface chunk download metrics into @@ -791,6 +798,10 @@ impl CloudFetchResultReader { #[async_trait] impl ResultReader for CloudFetchResultReader { + fn try_next_ready_batch(&mut self) -> Result { + self.try_next_batch() + } + async fn schema(&self) -> Result { self.provider.get_schema().await } @@ -826,6 +837,10 @@ impl InlineArrowReader { #[async_trait] impl ResultReader for InlineArrowReader { + fn try_next_ready_batch(&mut self) -> Result { + self.try_next_batch() + } + async fn schema(&self) -> Result { self.schema .clone() @@ -862,6 +877,10 @@ impl InlineStreamingReader { #[async_trait] impl ResultReader for InlineStreamingReader { + fn try_next_ready_batch(&mut self) -> Result { + self.try_next_batch() + } + async fn schema(&self) -> Result { self.schema.clone().ok_or_else(|| { Error::invalid_state().message("Schema not available for inline-Arrow streaming result") @@ -903,6 +922,10 @@ impl InMemoryReader { #[async_trait] impl ResultReader for InMemoryReader { + fn try_next_ready_batch(&mut self) -> Result { + self.try_next_batch() + } + async fn schema(&self) -> Result { Ok(self.schema.clone()) } @@ -933,6 +956,10 @@ impl EmptyReader { #[async_trait] impl ResultReader for EmptyReader { + fn try_next_ready_batch(&mut self) -> Result { + self.try_next_batch() + } + async fn schema(&self) -> Result { Ok(self.schema.clone()) } diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 4c5c82ce..e7a68361 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -297,6 +297,12 @@ impl ResultReader for ResultPostProcessor { Ok(Some(self.process_batch(batch)?)) } + fn try_next_ready_batch(&mut self) -> Result { + self.inner + .try_next_ready_batch()? + .map_ready(|batch| 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)) diff --git a/src/result_stream.rs b/src/result_stream.rs index 721424e1..6faabe98 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -474,8 +474,8 @@ pub struct ResultStream { /// `next_row_in_batch` reads and increments. current_row_idx: usize, - /// Flips to `true` once the wrapped reader returns its first - /// `None`. Subsequent `next_batch` calls short-circuit to + /// Flips to `true` when a normal fetch or first-batch peek observes + /// the end. Ready-only lookahead leaves this false. Later `next_batch` calls return /// `Ok(None)` without re-entering the reader — saves a wasted /// call on readers whose `next_batch` is non-trivial (CloudFetch /// in particular checks state and may take a runtime tick). @@ -714,7 +714,11 @@ impl ResultStream { // A batch buffered by `peek_first_batch` is replayed here first, // so a non-consuming peek doesn't steal it from the caller. if let Some(batch) = self.prefetched.take() { - self.set_current_batch(batch.map_err(|error| *error)?); + let batch = batch.map_err(|error| { + self.finalize_telemetry(Some(&error)); + *error + })?; + self.set_current_batch(batch); return Ok(self.current.as_ref()); } if self.exhausted { @@ -747,14 +751,40 @@ 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> { + self.try_next_batch_inner(true) + } + + /// Non-blocking lookahead for bindings packing ready batches. Errors and + /// end-of-stream do not finalize telemetry or clear the current batch. + /// `Ready` advances the stream, replaces `current`, and resets the row cursor. + /// Call `next_batch` (or `try_next_batch`) to deliver a buffered error or + /// observe the end and finalize consumption. Readers may opt out of probing. + /// + /// `Pending` can persist indefinitely for opt-out readers or a buffered + /// error. Repeated calls need not make progress; fall back to `next_batch` + /// to await the next outcome rather than polling this method alone. + pub fn try_next_ready_batch(&mut self) -> Result> { + self.try_next_batch_inner(false) + } + + fn try_next_batch_inner(&mut self, finalize: bool) -> Result> { + if !finalize && matches!(self.prefetched, Some(Err(_))) { + return Ok(TryNextBatch::Pending); + } if let Some(batch) = self.prefetched.take() { - self.set_current_batch(batch.map_err(|error| *error)?); + let batch = batch.map_err(|error| { + self.finalize_telemetry(Some(&error)); + *error + })?; + 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); + if finalize { + self.finalize_telemetry(None); + } return Ok(TryNextBatch::End); } @@ -762,7 +792,12 @@ impl ResultStream { .reader .as_mut() .expect("ResultStream reader is present until into_owned_batches consumes it"); - match reader.try_next_batch() { + let next = if finalize { + reader.try_next_batch() + } else { + reader.try_next_ready_batch() + }; + match next { Ok(crate::reader::TryNextBatch::Ready(batch)) => { self.set_current_batch(ResultBatch::Arrow(batch)); Ok(TryNextBatch::Ready( @@ -770,6 +805,7 @@ impl ResultStream { )) } Ok(crate::reader::TryNextBatch::Pending) => Ok(TryNextBatch::Pending), + Ok(crate::reader::TryNextBatch::End) if !finalize => Ok(TryNextBatch::End), Ok(crate::reader::TryNextBatch::End) => { self.current = None; self.current_row_idx = 0; @@ -777,6 +813,10 @@ impl ResultStream { self.finalize_telemetry(None); Ok(TryNextBatch::End) } + Err(error) if !finalize => { + self.prefetched = Some(Err(Box::new(error))); + Ok(TryNextBatch::Pending) + } Err(error) => { self.finalize_telemetry(Some(&error)); Err(error) @@ -979,6 +1019,9 @@ impl Iterator for OwnedBatchIter { } Err(error) => { self.done = true; + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), Some(&error), true); + } Some(Err(*error)) } }; @@ -1365,6 +1408,88 @@ mod tests { assert!(stream.next_batch().await.unwrap().is_none()); } + #[tokio::test] + async fn ready_lookahead_does_not_finalize_end_before_payload_delivery() { + for close_before_end in [false, true] { + let schema = schema_for(vec![Field::new("a", DataType::Int32, false)]); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![1]))]).unwrap(); + let mut stream = stream_with(batch).await; + stream.attach_telemetry(StatementTelemetry::noop()); + assert!(stream.next_batch().await.unwrap().is_some()); + assert!(matches!( + stream.try_next_ready_batch().unwrap(), + TryNextBatch::End + )); + assert!(stream.current().is_some()); + assert!(!stream.exhausted); + assert!(!stream.telemetry.as_ref().unwrap().finalized); + assert!(!stream.telemetry.as_ref().unwrap().consumed_recorded); + if close_before_end { + stream.finish_telemetry(); + assert!(!stream.telemetry.as_ref().unwrap().consumed_recorded); + } else { + assert!(stream.next_batch().await.unwrap().is_none()); + assert!(stream.telemetry.as_ref().unwrap().consumed_recorded); + } + assert!(stream.telemetry.as_ref().unwrap().finalized); + } + } + + #[tokio::test] + async fn ready_lookahead_preserves_unconsumed_empty_stream() { + let schema = schema_for(vec![Field::new("a", DataType::Int32, false)]); + let mut stream = ResultStream::from_reader(Box::new(InMemoryReader::new(schema, vec![]))) + .await + .unwrap(); + stream.attach_telemetry(StatementTelemetry::noop()); + assert!(stream.peek_first_batch().await.unwrap().is_none()); + assert!(matches!( + stream.try_next_ready_batch().unwrap(), + TryNextBatch::End + )); + assert!(!stream.telemetry.as_ref().unwrap().finalized); + assert!(stream.next_batch().await.unwrap().is_none()); + assert!(stream.telemetry.as_ref().unwrap().finalized); + } + + #[tokio::test] + async fn ready_lookahead_falls_back_for_non_polling_readers() { + struct NonPollingReader(std::vec::IntoIter, SchemaRef); + + #[async_trait::async_trait] + impl crate::reader::ResultReader for NonPollingReader { + async fn schema(&self) -> Result { + Ok(self.1.clone()) + } + + async fn next_batch(&mut self) -> Result> { + Ok(self.0.next()) + } + } + + let batch = + RecordBatch::try_from_iter([("n", Arc::new(Int32Array::from(vec![13])) as ArrayRef)]) + .unwrap(); + let mut stream = ResultStream::from_reader(Box::new(NonPollingReader( + vec![batch.clone(), batch.clone()].into_iter(), + batch.schema(), + ))) + .await + .unwrap(); + for _ in 0..2 { + assert!(matches!( + stream.try_next_ready_batch().unwrap(), + TryNextBatch::Pending + )); + let Some(ResultBatch::Arrow(actual)) = stream.next_batch().await.unwrap() else { + panic!("blocking fetch must still return the next batch"); + }; + assert_eq!(actual, &batch); + } + assert!(stream.next_batch().await.unwrap().is_none()); + } + #[tokio::test] async fn next_batch_replays_peek_error() { for nonblocking in [false, true] { diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 42505bc7..a818ab0b 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -367,6 +367,113 @@ mod tests { } } + struct BatchThenOneShotErrorReader { + schema: Arc, + batch: Option, + error_pending: bool, + } + + #[async_trait] + impl ResultReader for BatchThenOneShotErrorReader { + async fn schema(&self) -> crate::Result { + Ok(self.schema.clone()) + } + + async fn next_batch(&mut self) -> crate::Result> { + match self.try_next_batch()? { + crate::reader::TryNextBatch::Ready(batch) => Ok(Some(batch)), + crate::reader::TryNextBatch::End => Ok(None), + _ => unreachable!(), + } + } + + fn try_next_batch(&mut self) -> crate::Result { + if let Some(batch) = self.batch.take() { + return Ok(crate::reader::TryNextBatch::Ready(batch)); + } + if std::mem::take(&mut self.error_pending) { + return Err(KernelError::internal().message("one-shot lookahead failure")); + } + Ok(crate::reader::TryNextBatch::End) + } + + fn try_next_ready_batch(&mut self) -> crate::Result { + self.try_next_batch() + } + } + + #[tokio::test] + async fn lookahead_error_telemetry_matches_normal_fetch_and_early_close() { + for lookahead in [false, true] { + for deliver_error in [false, true] { + for delivery in [0, 1, 2] { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let batch = RecordBatch::try_from_iter([( + "n", + Arc::new(arrow_array::Int32Array::from(vec![Some(13), None])) + as arrow_array::ArrayRef, + )]) + .unwrap(); + let mut stream = + ResultStream::from_reader(Box::new(BatchThenOneShotErrorReader { + schema: batch.schema(), + batch: Some(batch), + error_pending: true, + })) + .await + .unwrap(); + stream.attach_telemetry(StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + )); + assert!(stream.next_batch().await.unwrap().is_some()); + if lookahead { + for _ in 0..2 { + assert!(matches!( + stream.try_next_ready_batch().unwrap(), + crate::result_stream::TryNextBatch::Pending + )); + } + assert!(stream.current().is_some()); + } + assert!(connection.statement_events.lock().unwrap().is_empty()); + if deliver_error && delivery == 2 { + let mut batches = stream.into_owned_batches(); + let error = batches.next().unwrap().unwrap_err(); + assert_eq!(error.code, ErrorCode::Internal); + assert_eq!(error.message, "one-shot lookahead failure"); + assert!(batches.next().is_none()); + drop(batches); + } else { + if deliver_error { + let error = if delivery == 1 { + stream.try_next_batch().unwrap_err() + } else { + stream.next_batch().await.unwrap_err() + }; + assert_eq!(error.code, ErrorCode::Internal); + assert_eq!(error.message, "one-shot lookahead failure"); + assert!(stream.next_batch().await.unwrap().is_none()); + } + stream.finish_telemetry(); + drop(stream); + } + let events = connection.statement_events.lock().unwrap(); + assert_eq!(events.len(), 1); + assert_eq!( + events[0].error_code, + deliver_error.then_some(ErrorCode::Internal) + ); + assert_eq!( + events[0].context.consumption_latency.is_some(), + deliver_error + ); + } + } + } + } + #[tokio::test] async fn peek_first_batch_error_finalizes_statement_with_error_before_drop() { let connection = Arc::new(CapturingConnectionTelemetry::default());