From 626ae3296ac6498f9156f503d544e0df39707127 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 01:14:49 +0000 Subject: [PATCH 01/10] perf(napi): pack ready result batches into fewer IPC payloads Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/NEXT_CHANGELOG.md | 2 + napi/src/async_statement.rs | 34 +--- napi/src/result.rs | 372 +++++++++++++++++++++++++++++++++++- napi/src/statement.rs | 74 +++---- 4 files changed, 404 insertions(+), 78 deletions(-) diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index d5ca462e..c4e5b1cd 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 bounded IPC payloads to reduce Node.js crossings, without waiting for another download. + ### Updated ### Fixed 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/result.rs b/napi/src/result.rs index 2573bb84..4d121449 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -17,22 +17,24 @@ //! 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 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 +/// 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, } @@ -68,6 +70,10 @@ 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}")), @@ -81,12 +87,16 @@ pub(crate) fn encode_ipc_stream( // 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; + let estimated = batches + .iter() + .map(RecordBatch::get_array_memory_size) + .sum::() + + 4096; 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 +104,99 @@ pub(crate) fn encode_ipc_stream( Ok(buf) } +pub(crate) trait BatchSource: Send { + fn next_batch( + &mut self, + ) -> impl std::future::Future>> + Send; + + fn try_next_batch(&mut self) -> databricks_sql_kernel::Result>; +} + +impl BatchSource for ResultStream { + async fn next_batch(&mut self) -> databricks_sql_kernel::Result> { + self.next_batch().await + } + + fn try_next_batch(&mut self) -> databricks_sql_kernel::Result> { + self.try_next_batch() + } +} + +pub(crate) struct IpcStream { + pub(crate) source: Source, + pending: Option>, +} + +impl IpcStream { + pub(crate) fn new(source: Source) -> Self { + Self { + source, + pending: None, + } + } + + pub(crate) async fn next( + &mut self, + schema: &SchemaRef, + binding_name: &str, + ) -> napi::Result>> { + 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 = first.get_array_memory_size(); + let mut batches = vec![first]; + while rows < 16_384 && bytes < 4 * 1024 * 1024 && batches.len() < 16 { + let candidate = match self.source.try_next_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(_) => Err(napi_err_from_kernel( + KernelError::invalid_argument() + .message("unsupported non-blocking result state"), + )), + }; + let candidate = match candidate { + Ok(batch) => batch, + Err(error) => { + self.pending = Some(Err(error)); + break; + } + }; + let candidate_bytes = candidate.get_array_memory_size(); + if candidate.num_rows() > 16_384 - rows || candidate_bytes > 4 * 1024 * 1024 - 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 +239,259 @@ mod tests { assert_eq!(decoded[0].num_rows(), 3); assert_eq!(decoded[0].schema().fields(), schema.fields()); } + + struct Source { + items: std::collections::VecDeque>>, + current: Option, + awaits: usize, + probes: usize, + } + + impl Source { + fn new(batches: Vec) -> Self { + Self { + items: batches.into_iter().map(|batch| Ok(Some(batch))).collect(), + current: None, + awaits: 0, + probes: 0, + } + } + + fn take(&mut self) -> databricks_sql_kernel::Result> { + 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)) => 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()? { + TryNextBatch::Ready(batch) => Ok(Some(batch)), + TryNextBatch::End => Ok(None), + _ => panic!("packing must not await a pending batch"), + } + } + + fn try_next_batch(&mut self) -> databricks_sql_kernel::Result> { + self.probes += 1; + self.take() + } + } + + 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(3 * 1024 * 1024)), + 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()])); + assert_eq!(next(&mut stream, &schema).await, vec![batch.clone()]); + assert_eq!(next(&mut stream, &schema).await, vec![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_eq!(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, 1); + } + + #[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 nullable_arrow_types_and_metadata_round_trip_across_messages() { + use arrow_array::*; + 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)), + ]; + 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 changing_dictionaries_keep_each_batch_values() { + use arrow_array::{types::Int8Type, DictionaryArray}; + let batches = ["first", "second"].map(|value| { + let array = DictionaryArray::::from_iter([Some(value), None]); + RecordBatch::try_from_iter([("dictionary", Arc::new(array) as arrow_array::ArrayRef)]) + .unwrap() + }); + let schema = batches[0].schema(); + let mut stream = IpcStream::new(Source::new(batches.to_vec())); + assert_eq!(next(&mut stream, &schema).await, batches); + } } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 40d682d2..29478d4f 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,16 @@ enum AnyInner { Metadata(ResultStream), } -impl AnyInner { +impl BatchSource for AnyInner { + fn try_next_batch( + &mut self, + ) -> databricks_sql_kernel::Result> { + match self { + AnyInner::Executed(statement) => statement.executed.try_next_batch(), + AnyInner::Metadata(stream) => stream.try_next_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 +128,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 +163,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 +188,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 +232,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 +266,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 +285,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 +313,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 +323,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 +345,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 +416,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 +465,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 From 040b56ded7b8e58718d36c2321af98b5470a21dc Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 01:30:42 +0000 Subject: [PATCH 02/10] test(napi): pin packed IPC bounds and nullable values Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/index.d.ts | 16 ++++++++-------- napi/src/result.rs | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 39 insertions(+), 11 deletions(-) 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/result.rs b/napi/src/result.rs index 4d121449..275419a5 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -339,8 +339,12 @@ mod tests { 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()])); - assert_eq!(next(&mut stream, &schema).await, vec![batch.clone()]); - assert_eq!(next(&mut stream, &schema).await, vec![batch]); + 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()); } @@ -356,7 +360,7 @@ mod tests { ) .unwrap(); let mut stream = IpcStream::new(Source::new(vec![batch.clone(), batch.clone()])); - assert_eq!(next(&mut stream, &schema).await, vec![batch]); + assert!(next(&mut stream, &schema).await == vec![batch]); assert_eq!(stream.source.probes, 0); } @@ -416,7 +420,17 @@ mod tests { #[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])), @@ -463,6 +477,20 @@ mod tests { 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() From 61cb656676ddfc3797f16629831c5f699469543f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 01:43:54 +0000 Subject: [PATCH 03/10] fix(napi): preserve end-of-stream lifecycle during batch lookahead Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 ++ napi/src/result.rs | 2 +- napi/src/statement.rs | 7 +++-- src/result_stream.rs | 61 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8577a424..e3da41e7 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()` supports non-blocking lookahead without finalizing end-of-stream before a binding delivers its buffered payload. + - A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C ABI for driver-manager loading from other languages. diff --git a/napi/src/result.rs b/napi/src/result.rs index 275419a5..c13191dc 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -118,7 +118,7 @@ impl BatchSource for ResultStream { } fn try_next_batch(&mut self) -> databricks_sql_kernel::Result> { - self.try_next_batch() + self.try_next_ready_batch() } } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 29478d4f..fb831770 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -84,8 +84,11 @@ impl BatchSource for AnyInner { &mut self, ) -> databricks_sql_kernel::Result> { match self { - AnyInner::Executed(statement) => statement.executed.try_next_batch(), - AnyInner::Metadata(stream) => stream.try_next_batch(), + AnyInner::Executed(statement) => statement + .executed + .result_stream_mut() + .try_next_ready_batch(), + AnyInner::Metadata(stream) => stream.try_next_ready_batch(), } } diff --git a/src/result_stream.rs b/src/result_stream.rs index 721424e1..38c48c7a 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -747,6 +747,17 @@ 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. End-of-stream + /// leaves the current batch and telemetry untouched until a normal fetch, + /// so returning a payload does not prematurely mark it fully consumed. + pub fn try_next_ready_batch(&mut self) -> Result> { + self.try_next_batch_inner(false) + } + + fn try_next_batch_inner(&mut self, finalize_end: bool) -> Result> { if let Some(batch) = self.prefetched.take() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(TryNextBatch::Ready( @@ -754,7 +765,9 @@ impl ResultStream { )); } if self.exhausted { - self.finalize_telemetry(None); + if finalize_end { + self.finalize_telemetry(None); + } return Ok(TryNextBatch::End); } @@ -770,6 +783,7 @@ impl ResultStream { )) } Ok(crate::reader::TryNextBatch::Pending) => Ok(TryNextBatch::Pending), + Ok(crate::reader::TryNextBatch::End) if !finalize_end => Ok(TryNextBatch::End), Ok(crate::reader::TryNextBatch::End) => { self.current = None; self.current_row_idx = 0; @@ -1365,6 +1379,51 @@ 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 next_batch_replays_peek_error() { for nonblocking in [false, true] { From bb926642868dff45fda0561cd4f86c63286ca304 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 02:54:47 +0000 Subject: [PATCH 04/10] docs(napi): clarify shared IPC writer documentation Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/result.rs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/napi/src/result.rs b/napi/src/result.rs index c13191dc..046a7274 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -51,21 +51,9 @@ 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>, From ed5e75dc0e334ff6a67ffa4710e39e2ed2cdfd03 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:04:16 +0000 Subject: [PATCH 05/10] fix(napi): defer speculative errors and budget sliced result data Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 +- napi/src/connection.rs | 163 +++++++++++++++++++++++++++++++ napi/src/result.rs | 76 +++++++++----- napi/src/statement.rs | 2 +- src/metadata/thrift_shape.rs | 6 ++ src/reader/mod.rs | 27 +++++ src/reader/post_processor/mod.rs | 6 ++ src/result_stream.rs | 79 +++++++++++++-- src/telemetry/statement.rs | 107 ++++++++++++++++++++ 9 files changed, 434 insertions(+), 34 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index e3da41e7..ed983565 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,7 +11,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added -- `ResultStream::try_next_ready_batch()` supports non-blocking lookahead without finalizing end-of-stream before a binding delivers its buffered payload. +- `ResultStream::try_next_ready_batch()` supports optional non-blocking lookahead without finalizing errors or end-of-stream before the consumer receives them. - A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C ABI for driver-manager loading from other languages. diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 7aba91ff..1ec5da7f 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -702,6 +702,169 @@ 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 in [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; + 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": 1, "total_row_count": 9, + "total_byte_count": ipc.len(), "truncated": false + }, + "result": { "external_links": [{ + "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() + }] } + }))) + .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; + 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) + .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); + tokio::time::sleep(Duration::from_millis(50)).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" + ); + + if early_close { + statement.close().await.unwrap(); + } else { + assert!(statement.fetch_next_batch().await.unwrap().is_none()); + } + 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); + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("normal completion must close and export exactly one statement event"); + statement.close().await.unwrap(); + connection.close().await.unwrap(); + } + } + #[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 046a7274..a8d8e2ed 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -67,19 +67,13 @@ fn encode_ipc_batches(schema: &SchemaRef, batches: &[RecordBatch]) -> napi::Resu 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. + // IPC-decoded arrays can share a much larger backing buffer. Reserve for + // the slices being encoded, with slack for schema and message framing. let estimated = batches .iter() - .map(RecordBatch::get_array_memory_size) - .sum::() - + 4096; + .map(sliced_batch_bytes) + .fold(4096usize, usize::saturating_add) + .min(4 * 1024 * 1024); let mut buf: Vec = Vec::with_capacity(estimated); { let mut writer = @@ -92,21 +86,31 @@ fn encode_ipc_batches(schema: &SchemaRef, batches: &[RecordBatch]) -> napi::Resu 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) +} + pub(crate) trait BatchSource: Send { fn next_batch( &mut self, ) -> impl std::future::Future>> + Send; - fn try_next_batch(&mut self) -> databricks_sql_kernel::Result>; + 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> { - self.next_batch().await + ResultStream::next_batch(self).await } - fn try_next_batch(&mut self) -> databricks_sql_kernel::Result> { - self.try_next_ready_batch() + fn try_next_ready_batch(&mut self) -> databricks_sql_kernel::Result> { + ResultStream::try_next_ready_batch(self) } } @@ -143,17 +147,14 @@ impl IpcStream { } }; let mut rows = first.num_rows(); - let mut bytes = first.get_array_memory_size(); + let mut bytes = sliced_batch_bytes(&first); let mut batches = vec![first]; while rows < 16_384 && bytes < 4 * 1024 * 1024 && batches.len() < 16 { - let candidate = match self.source.try_next_batch() { + 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(_) => Err(napi_err_from_kernel( - KernelError::invalid_argument() - .message("unsupported non-blocking result state"), - )), + Ok(_) => break, }; let candidate = match candidate { Ok(batch) => batch, @@ -162,7 +163,7 @@ impl IpcStream { break; } }; - let candidate_bytes = candidate.get_array_memory_size(); + let candidate_bytes = sliced_batch_bytes(&candidate); if candidate.num_rows() > 16_384 - rows || candidate_bytes > 4 * 1024 * 1024 - bytes { self.pending = Some(Ok(candidate)); break; @@ -268,7 +269,7 @@ mod tests { } } - fn try_next_batch(&mut self) -> databricks_sql_kernel::Result> { + fn try_next_ready_batch(&mut self) -> databricks_sql_kernel::Result> { self.probes += 1; self.take() } @@ -406,6 +407,35 @@ mod tests { 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..34).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() > 4 * 1024 * 1024); + assert!(sliced_batch_bytes(&decoded) < 800_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() < 4 * 1024 * 1024); + 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}; diff --git a/napi/src/statement.rs b/napi/src/statement.rs index fb831770..6d1be605 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -80,7 +80,7 @@ enum AnyInner { } impl BatchSource for AnyInner { - fn try_next_batch( + fn try_next_ready_batch( &mut self, ) -> databricks_sql_kernel::Result> { match self { diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 2a755096..eb9262c5 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()? diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 33e7816d..92b8fc24 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -716,6 +716,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 @@ -779,6 +786,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 } @@ -814,6 +825,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() @@ -850,6 +865,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") @@ -891,6 +910,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()) } @@ -921,6 +944,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 a57b5d5d..bb414aca 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -295,6 +295,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 38c48c7a..841da1c2 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -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 { @@ -750,22 +754,30 @@ impl ResultStream { self.try_next_batch_inner(true) } - /// Non-blocking lookahead for bindings packing ready batches. End-of-stream - /// leaves the current batch and telemetry untouched until a normal fetch, - /// so returning a payload does not prematurely mark it fully consumed. + /// Non-blocking lookahead for bindings packing ready batches. Errors and + /// end-of-stream do not finalize telemetry or clear the current batch. + /// 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. pub fn try_next_ready_batch(&mut self) -> Result> { self.try_next_batch_inner(false) } - fn try_next_batch_inner(&mut self, finalize_end: bool) -> Result> { + 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 { - if finalize_end { + if finalize { self.finalize_telemetry(None); } return Ok(TryNextBatch::End); @@ -775,7 +787,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( @@ -783,7 +800,7 @@ impl ResultStream { )) } Ok(crate::reader::TryNextBatch::Pending) => Ok(TryNextBatch::Pending), - Ok(crate::reader::TryNextBatch::End) if !finalize_end => Ok(TryNextBatch::End), + Ok(crate::reader::TryNextBatch::End) if !finalize => Ok(TryNextBatch::End), Ok(crate::reader::TryNextBatch::End) => { self.current = None; self.current_row_idx = 0; @@ -791,6 +808,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) @@ -993,6 +1014,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)) } }; @@ -1424,6 +1448,43 @@ mod tests { 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()); From 8d9a579c11197da6419a234eff827ae3b9545881 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 05:39:48 +0000 Subject: [PATCH 06/10] fix(napi): bound payloads and protect dictionary and error paths Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/connection.rs | 100 ++++++++++++++++++++---- napi/src/result.rs | 167 +++++++++++++++++++++++++++++++++++------ napi/src/statement.rs | 11 +++ 3 files changed, 242 insertions(+), 36 deletions(-) diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 1ec5da7f..e29542ac 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -739,7 +739,7 @@ mod tests { use databricks_sql_kernel::TelemetryConfig; use std::time::Duration; - for early_close in [false, true] { + for (early_close, failed_download) in [(false, false), (true, false), (false, true)] { let server = MockServer::start().await; let batch = RecordBatch::try_from_iter([( "n", @@ -767,6 +767,28 @@ mod tests { .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!({ @@ -777,15 +799,10 @@ mod tests { "schema": { "column_count": 1, "columns": [{ "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 }] }, - "total_chunk_count": 1, "total_row_count": 9, + "total_chunk_count": links.len(), "total_row_count": if failed_download { 12 } else { 9 }, "total_byte_count": ipc.len(), "truncated": false }, - "result": { "external_links": [{ - "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() - }] } + "result": { "external_links": links } }))) .mount(&server) .await; @@ -808,6 +825,9 @@ mod tests { 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 { @@ -815,6 +835,7 @@ mod tests { identity_federation_client_id: None, }) .telemetry(telemetry) + .http(http) .open() .await .unwrap(); @@ -833,7 +854,23 @@ mod tests { .unwrap(); assert_eq!(batches.len(), 3); assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 9); - tokio::time::sleep(Duration::from_millis(50)).await; + 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!( @@ -841,27 +878,64 @@ mod tests { "lookahead must not finalize statement telemetry" ); - if early_close { + 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()); } - tokio::time::timeout(Duration::from_secs(2), async { + 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 - .expect("normal completion must close and export exactly one statement event"); + .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"); } } diff --git a/napi/src/result.rs b/napi/src/result.rs index a8d8e2ed..59632a5a 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -21,7 +21,7 @@ use arrow_array::RecordBatch; use arrow_ipc::writer::StreamWriter; -use arrow_schema::SchemaRef; +use arrow_schema::{DataType, SchemaRef}; use databricks_sql_kernel::{ result_stream::TryNextBatch, Error as KernelError, ResultBatch, ResultStream, }; @@ -29,6 +29,8 @@ use napi::bindgen_prelude::Buffer; use crate::error::napi_err_from_kernel; +const IPC_TARGET_BYTES: usize = 2 * 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)] @@ -73,7 +75,7 @@ fn encode_ipc_batches(schema: &SchemaRef, batches: &[RecordBatch]) -> napi::Resu .iter() .map(sliced_batch_bytes) .fold(4096usize, usize::saturating_add) - .min(4 * 1024 * 1024); + .min(IPC_TARGET_BYTES); let mut buf: Vec = Vec::with_capacity(estimated); { let mut writer = @@ -96,6 +98,28 @@ fn sliced_batch_bytes(batch: &RecordBatch) -> usize { .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, @@ -117,6 +141,7 @@ impl BatchSource for ResultStream { pub(crate) struct IpcStream { pub(crate) source: Source, pending: Option>, + packing_allowed: Option, } impl IpcStream { @@ -124,6 +149,7 @@ impl IpcStream { Self { source, pending: None, + packing_allowed: None, } } @@ -132,6 +158,13 @@ impl IpcStream { 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 => { @@ -149,7 +182,7 @@ impl IpcStream { let mut rows = first.num_rows(); let mut bytes = sliced_batch_bytes(&first); let mut batches = vec![first]; - while rows < 16_384 && bytes < 4 * 1024 * 1024 && batches.len() < 16 { + 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, @@ -164,7 +197,7 @@ impl IpcStream { } }; let candidate_bytes = sliced_batch_bytes(&candidate); - if candidate.num_rows() > 16_384 - rows || candidate_bytes > 4 * 1024 * 1024 - bytes { + if candidate.num_rows() > 16_384 - rows || candidate_bytes > IPC_TARGET_BYTES - bytes { self.pending = Some(Ok(candidate)); break; } @@ -234,6 +267,7 @@ mod tests { current: Option, awaits: usize, probes: usize, + deferred_error: Option, } impl Source { @@ -243,16 +277,27 @@ mod tests { current: None, awaits: 0, probes: 0, + deferred_error: None, } } - fn take(&mut self) -> databricks_sql_kernel::Result> { + 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), } @@ -262,7 +307,7 @@ mod tests { impl BatchSource for Source { async fn next_batch(&mut self) -> databricks_sql_kernel::Result> { self.awaits += 1; - match self.take()? { + match self.take(false)? { TryNextBatch::Ready(batch) => Ok(Some(batch)), TryNextBatch::End => Ok(None), _ => panic!("packing must not await a pending batch"), @@ -271,7 +316,7 @@ mod tests { fn try_next_ready_batch(&mut self) -> databricks_sql_kernel::Result> { self.probes += 1; - self.take() + self.take(true) } } @@ -322,7 +367,7 @@ mod tests { 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(3 * 1024 * 1024)), + Some("x".repeat(IPC_TARGET_BYTES * 3 / 4)), None, ])); let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, true)])); @@ -392,7 +437,7 @@ mod tests { ); let error = stream.next(&make_schema(), "test").await.unwrap_err(); assert!(error.reason.contains("late download error")); - assert_eq!(stream.source.awaits, 1); + assert_eq!(stream.source.awaits, 2); } #[tokio::test] @@ -410,7 +455,7 @@ mod tests { #[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..34).map(|column| { + let batch = RecordBatch::try_from_iter((0..8).map(|column| { ( format!("column{column}"), Arc::new(Int64Array::from_iter( @@ -426,12 +471,12 @@ mod tests { .next() .unwrap() .unwrap(); - assert!(decoded.get_array_memory_size() > 4 * 1024 * 1024); - assert!(sliced_batch_bytes(&decoded) < 800_000); + 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() < 4 * 1024 * 1024); + assert!(bytes.len() < IPC_TARGET_BYTES); assert_eq!(decode(bytes), vec![decoded.clone(); 5]); assert_eq!(next(&mut stream, &schema).await, vec![decoded]); } @@ -529,15 +574,91 @@ mod tests { } #[tokio::test] - async fn changing_dictionaries_keep_each_batch_values() { - use arrow_array::{types::Int8Type, DictionaryArray}; - let batches = ["first", "second"].map(|value| { - let array = DictionaryArray::::from_iter([Some(value), None]); - RecordBatch::try_from_iter([("dictionary", Arc::new(array) as arrow_array::ArrayRef)]) - .unwrap() - }); - let schema = batches[0].schema(); - let mut stream = IpcStream::new(Source::new(batches.to_vec())); - assert_eq!(next(&mut stream, &schema).await, batches); + async fn dictionary_schemas_never_probe_or_pack_batches() { + 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 Ok(directory) = std::env::var("DICT_FIXTURE_DIR") { + let directory = std::path::PathBuf::from(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 6d1be605..e64d7588 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -531,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::*; From df2af62624348c099d58c40f31d9e903c60006a1 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 05:59:59 +0000 Subject: [PATCH 07/10] perf(napi): preserve materialization latency with a 1 MiB cap Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/NEXT_CHANGELOG.md | 2 +- napi/src/result.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index c4e5b1cd..93ec8a99 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -16,7 +16,7 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Changed -- Result fetches pack already-buffered Arrow batches into bounded IPC payloads to reduce Node.js crossings, without waiting for another download. +- 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 diff --git a/napi/src/result.rs b/napi/src/result.rs index 59632a5a..ad1d3da1 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -29,7 +29,7 @@ use napi::bindgen_prelude::Buffer; use crate::error::napi_err_from_kernel; -const IPC_TARGET_BYTES: usize = 2 * 1024 * 1024; +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). From 37b88791cf37f5130343ebd502eb6d7daa23cc91 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 07:25:33 +0000 Subject: [PATCH 08/10] fix(napi): reserve complete IPC output including message framing Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/result.rs | 41 +++++++++++++++++++++++++++++++++++++++-- src/result_stream.rs | 8 ++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/napi/src/result.rs b/napi/src/result.rs index ad1d3da1..68edb2be 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -71,11 +71,15 @@ fn encode_ipc_batches(schema: &SchemaRef, batches: &[RecordBatch]) -> napi::Resu } // 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) - .fold(4096usize, usize::saturating_add) - .min(IPC_TARGET_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 = @@ -262,6 +266,39 @@ mod tests { 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, diff --git a/src/result_stream.rs b/src/result_stream.rs index 841da1c2..28dcb259 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). @@ -758,6 +758,10 @@ impl ResultStream { /// end-of-stream do not finalize telemetry or clear the current batch. /// 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) } From 85ce37ae66fb3e53fa14fc9315fb88c8afc1061a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 07:33:15 +0000 Subject: [PATCH 09/10] test(napi): isolate optional dictionary fixture export Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/src/result.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/napi/src/result.rs b/napi/src/result.rs index 68edb2be..d227aee8 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -612,6 +612,19 @@ mod tests { #[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| { @@ -632,9 +645,8 @@ mod tests { 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 Ok(directory) = std::env::var("DICT_FIXTURE_DIR") { - let directory = std::path::PathBuf::from(directory); - std::fs::create_dir_all(&directory).unwrap(); + if let Some(directory) = directory { + std::fs::create_dir_all(directory).unwrap(); std::fs::write(directory.join(format!("{nested}-{index}.arrow")), &bytes) .unwrap(); } From 61fad3884431594a098f4b998613bf8f2088239c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 07:39:08 +0000 Subject: [PATCH 10/10] test(kernel): cover ready metadata reshaping and clarify stream advancement Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 +- src/metadata/thrift_shape.rs | 63 ++++++++++++++++++++++++++++++++++++ src/result_stream.rs | 1 + 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ed983565..e52a6a84 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,7 +11,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added -- `ResultStream::try_next_ready_batch()` supports optional non-blocking lookahead without finalizing errors or end-of-stream before the consumer receives them. +- `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. - A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C ABI for driver-manager loading from other languages. diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index eb9262c5..6c241d89 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -1250,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/result_stream.rs b/src/result_stream.rs index 28dcb259..6faabe98 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -756,6 +756,7 @@ impl ResultStream { /// 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. ///