From 10b40f34c4133ce3cbeab8da400086e32c85787b Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 20:55:40 +0000 Subject: [PATCH 1/7] perf(python): return small results as Python rows without pyarrow A one-row result costs the Python driver far more than the row: importing the pyarrow schema and batch over the C data interface (each import releases and re-takes the GIL), a metadata-fingerprinting schema comparison, and to_pylist() per column. ExecutedStatement.fetch_all_rows(max_rows, nan_ok) and the same on ResultStream return all remaining rows as tuples of Python values built in Rust, equal to what pyarrow's to_pylist() returns for the types they convert (ints, floats, bool, null, strings, binary, decimal, date32, and s/ms/us timestamps with or without a time zone). They return None for larger results, other types, NaN (unless nan_ok) and values outside Python's date range, and the Arrow fetches then return the batches already read. schema_key() returns a SchemaKey that compares two results' schemas in Rust, so callers can cache what they derive from a schema without building a pyarrow.Schema. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 7 + pyo3/src/fetch.rs | 55 ++++ pyo3/src/lib.rs | 3 + pyo3/src/result_stream.rs | 60 +++- pyo3/src/rows.rs | 625 ++++++++++++++++++++++++++++++++++++++ pyo3/src/statement.rs | 67 +++- pyo3/tests/test_rows.py | 287 +++++++++++++++++ 7 files changed, 1097 insertions(+), 7 deletions(-) create mode 100644 pyo3/src/rows.rs create mode 100644 pyo3/tests/test_rows.py diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..52eec8a0 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -12,6 +12,13 @@ changes go in the root `NEXT_CHANGELOG.md`. ## [Unreleased] ### Added +- `ExecutedStatement.fetch_all_rows(max_rows, nan_ok=False)` (and the same + on `ResultStream`) returns all remaining rows as tuples of Python values, + equal to what pyarrow's `to_pylist()` returns, when there are at most + `max_rows` of them and every column type is supported; otherwise it + returns `None` and the Arrow fetches return the batches it read. + `schema_key()` returns a `SchemaKey` that compares equal for equal result + schemas. Together they let callers handle small results without pyarrow. ### Changed diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 9e7d859c..8f30bcc8 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -25,6 +25,7 @@ use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream}; use pyo3::prelude::*; +use std::collections::VecDeque; use std::sync::Arc; use tokio::runtime::Runtime; @@ -105,6 +106,60 @@ pub(crate) fn drain_exec( }) } +/// Pull batches into `pending` until it holds more than `max_rows` rows or +/// the stream ends. Returns whether the stream ended. +pub(crate) fn fill( + runtime: &Runtime, + stream: &mut ResultStream, + pending: &mut VecDeque, + max_rows: usize, +) -> Result { + runtime.block_on(async { + let mut rows: usize = pending.iter().map(RecordBatch::num_rows).sum(); + while rows <= max_rows { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => { + rows += rb.num_rows(); + pending.push_back(rb.clone()); + } + Some(_) => { + return Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")); + } + None => return Ok(true), + } + } + Ok(false) + }) +} + +/// Like [`fill`], but drives the `ExecutedStatement` so auto-close-on-drain +/// fires once the stream is exhausted. +pub(crate) fn fill_exec( + runtime: &Runtime, + exec: &mut ExecutedStatement, + pending: &mut VecDeque, + max_rows: usize, +) -> Result { + runtime.block_on(async { + let mut rows: usize = pending.iter().map(RecordBatch::num_rows).sum(); + while rows <= max_rows { + match exec.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => { + rows += rb.num_rows(); + pending.push_back(rb.clone()); + } + Some(_) => { + return Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")); + } + None => return Ok(true), + } + } + Ok(false) + }) +} + /// Wrap a Vec of `RecordBatch` into a `pyarrow.Table`. Centralised /// so both `ExecutedStatement.fetch_all_arrow` and /// `ResultStream.fetch_all_arrow` produce identical Python objects. diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index f42ffa85..331d5975 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -40,6 +40,7 @@ mod logging; mod metadata; mod params; mod result_stream; +mod rows; mod runtime; mod session; mod statement; @@ -87,8 +88,10 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_function(wrap_pyfunction!(init_logging, m)?)?; m.add_function(wrap_pyfunction!(reset_logging, m)?)?; + m.add_function(wrap_pyfunction!(rows::rows_from_arrow, m)?)?; // Install the log bridge at module import so *any* consumer of the // bare wheel (the connector, integration tests, custom embedders) diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index cd193bb9..b92e6f95 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -26,11 +26,15 @@ //! the same code path through its `result_stream_mut()` borrow. use crate::fetch; +use crate::rows::{self, SchemaKey}; use crate::runtime::KernelRuntime; +use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::ResultStream as KResultStream; use pyo3::prelude::*; +use pyo3::types::PyList; +use std::collections::VecDeque; use std::sync::Arc; /// Python-facing borrowed result stream. @@ -40,23 +44,30 @@ pub(crate) struct ResultStream { /// Cached schema — survives `close()` so callers can still read /// the description after exhausting / closing the stream. schema: Arc, + /// Whether `fetch_all_rows` converts every column type of `schema`. + rows_supported: bool, } struct ResultStreamInner { stream: KResultStream, runtime: Arc, exhausted: bool, + /// Batches `fetch_all_rows` pulled but didn't convert; served first by + /// the Arrow fetches. + pending: VecDeque, } impl ResultStream { pub(crate) fn new(stream: KResultStream, runtime: Arc) -> Self { let schema = stream.schema(); Self { + rows_supported: rows::schema_is_supported(&schema), schema, inner: Some(ResultStreamInner { stream, runtime, exhausted: false, + pending: VecDeque::new(), }), } } @@ -69,10 +80,47 @@ impl ResultStream { self.schema.as_ref().to_pyarrow(py) } + /// See `ExecutedStatement.schema_key`. + fn schema_key(&self) -> SchemaKey { + SchemaKey::new(self.schema.clone()) + } + + /// See `ExecutedStatement.fetch_all_rows`. + #[pyo3(signature = (max_rows, nan_ok = false))] + fn fetch_all_rows<'py>( + &mut self, + py: Python<'py>, + max_rows: usize, + nan_ok: bool, + ) -> PyResult>> { + let inner = alive_mut!(self, "ResultStream"); + if !self.rows_supported { + return Ok(None); + } + if !inner.exhausted { + let runtime = inner.runtime.clone(); + inner.exhausted = run_sync_kernel!( + py, + fetch::fill(&runtime, &mut inner.stream, &mut inner.pending, max_rows) + )?; + } + rows::take_rows( + py, + &self.schema, + inner.exhausted, + &mut inner.pending, + max_rows, + nan_ok, + ) + } + /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` when /// exhausted. fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { let inner = alive_mut!(self, "ResultStream"); + if let Some(batch) = inner.pending.pop_front() { + return Ok(Some(batch.to_pyarrow(py)?)); + } if inner.exhausted { return Ok(None); } @@ -90,9 +138,15 @@ impl ResultStream { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ResultStream"); - let runtime = inner.runtime.clone(); - let batches = run_sync_kernel!(py, fetch::drain(&runtime, &mut inner.stream))?; - inner.exhausted = true; + let mut batches: Vec = inner.pending.drain(..).collect(); + if !inner.exhausted { + let runtime = inner.runtime.clone(); + batches.extend(run_sync_kernel!( + py, + fetch::drain(&runtime, &mut inner.stream) + )?); + inner.exhausted = true; + } fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/src/rows.rs b/pyo3/src/rows.rs new file mode 100644 index 00000000..eba7bdef --- /dev/null +++ b/pyo3/src/rows.rs @@ -0,0 +1,625 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Small results as Python rows, without pyarrow. +//! +//! Handing a one-row result to Python as a `pyarrow.RecordBatch` costs far +//! more than the row itself: the C data interface export and import of the +//! batch and its schema, then `to_pylist()` per column. `rows_to_py` builds +//! the rows' Python values directly, matching what pyarrow's `to_pylist()` +//! returns for each supported type, and declines (`None`) everything else so +//! callers fall back to the Arrow path. + +use arrow_array::cast::AsArray; +use arrow_array::types::{ + Date32Type, Decimal128Type, Decimal256Type, Float32Type, Float64Type, Int16Type, Int32Type, + Int64Type, Int8Type, TimestampMicrosecondType, TimestampMillisecondType, TimestampSecondType, + UInt16Type, UInt32Type, UInt64Type, UInt8Type, +}; +use arrow_array::{Array, ArrowPrimitiveType, PrimitiveArray, RecordBatch}; +use arrow_schema::{DataType, Schema, TimeUnit}; +use chrono::{Datelike, NaiveDate}; +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::{PyBool, PyBytes, PyFloat, PyList, PyString, PyTuple}; +use std::collections::hash_map::DefaultHasher; +use std::collections::VecDeque; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, OnceLock}; + +static DECIMAL: PyOnceLock> = PyOnceLock::new(); +static DATE: PyOnceLock> = PyOnceLock::new(); +static DATETIME: PyOnceLock> = PyOnceLock::new(); +static UTC: PyOnceLock> = PyOnceLock::new(); +static STRING_TO_TZINFO: PyOnceLock> = PyOnceLock::new(); + +/// Days from 0001-01-01 (day 1 of the proleptic Gregorian calendar) to +/// 1970-01-01. +const UNIX_EPOCH_DAYS_FROM_CE: i64 = 719_163; +const MICROS_PER_SECOND: i64 = 1_000_000; +const SECONDS_PER_DAY: i64 = 86_400; + +fn cached<'py>( + py: Python<'py>, + cell: &'static PyOnceLock>, + module: &str, + path: &[&str], +) -> PyResult> { + cell.get_or_try_init(py, || { + let mut value = py.import(module)?.into_any(); + for name in path { + value = value.getattr(*name)?; + } + Ok::<_, PyErr>(value.unbind()) + }) + .map(|value| value.bind(py).clone()) +} + +/// Whether `rows_to_py` converts columns of this type. +pub(crate) fn is_supported(data_type: &DataType) -> bool { + match data_type { + DataType::Null + | DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float32 + | DataType::Float64 + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Binary + | DataType::LargeBinary + | DataType::FixedSizeBinary(_) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) + | DataType::Date32 => true, + // pyarrow returns pandas Timestamps for nanoseconds when pandas is + // installed. + DataType::Timestamp(unit, _) => *unit != TimeUnit::Nanosecond, + _ => false, + } +} + +pub(crate) fn schema_is_supported(schema: &Schema) -> bool { + schema.fields().iter().all(|f| is_supported(f.data_type())) +} + +/// The rows in `pending` if the stream `ended` with at most `max_rows` of +/// them and they convert, clearing `pending`; otherwise `None`, leaving +/// `pending` for the Arrow fetches. +pub(crate) fn take_rows<'py>( + py: Python<'py>, + schema: &Schema, + ended: bool, + pending: &mut VecDeque, + max_rows: usize, + nan_ok: bool, +) -> PyResult>> { + if !ended || pending.iter().map(RecordBatch::num_rows).sum::() > max_rows { + return Ok(None); + } + let rows = rows_to_py(py, schema, pending.make_contiguous(), nan_ok)?; + if rows.is_some() { + pending.clear(); + } + Ok(rows) +} + +/// The rows of `batches` as a list of tuples, or `None` if a column can't be +/// converted here: an unsupported type, a batch whose column types differ +/// from `schema`'s, a value that Python's `date`/`datetime` can't hold, or +/// (unless `nan_ok`) a NaN float, whose conversion depends on the caller. +pub(crate) fn rows_to_py<'py>( + py: Python<'py>, + schema: &Schema, + batches: &[RecordBatch], + nan_ok: bool, +) -> PyResult>> { + let num_columns = schema.fields().len(); + let num_rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + let mut columns: Vec>> = (0..num_columns) + .map(|_| Vec::with_capacity(num_rows)) + .collect(); + let mut converter = Converter::new(py, nan_ok); + for batch in batches { + if batch.num_columns() != num_columns { + return Ok(None); + } + for ((field, array), out) in schema + .fields() + .iter() + .zip(batch.columns()) + .zip(columns.iter_mut()) + { + if array.data_type() != field.data_type() || !converter.convert(array.as_ref(), out)? { + return Ok(None); + } + } + } + let mut values: Vec<_> = columns.into_iter().map(Vec::into_iter).collect(); + let rows = (0..num_rows) + .map(|_| { + PyTuple::new( + py, + values + .iter_mut() + .map(|column| column.next().expect("one value per row")), + ) + }) + .collect::>>()?; + Ok(Some(PyList::new(py, rows)?)) +} + +macro_rules! ints { + ($self:expr, $array:expr, $out:expr, $type:ty) => {{ + let py = $self.py; + let a = $array.as_primitive::<$type>(); + $self.each(a, $out, |i| { + Ok(Some(a.value(i).into_pyobject(py)?.into_any())) + }) + }}; +} + +struct Converter<'py> { + py: Python<'py>, + nan_ok: bool, + none: Bound<'py, PyAny>, +} + +/// Python `date` fields for days since the Unix epoch, if in `date`'s range +/// (years 1 through 9999). +fn ymd(days: i64) -> Option<(i32, u32, u32)> { + let days = i32::try_from(days.checked_add(UNIX_EPOCH_DAYS_FROM_CE)?).ok()?; + let date = NaiveDate::from_num_days_from_ce_opt(days)?; + (1..=9999) + .contains(&date.year()) + .then(|| (date.year(), date.month(), date.day())) +} + +impl<'py> Converter<'py> { + fn new(py: Python<'py>, nan_ok: bool) -> Self { + Self { + py, + nan_ok, + none: py.None().into_bound(py), + } + } + + /// Append the Python values of `array` to `out`; `false` if it can't be + /// converted here. + fn convert(&mut self, array: &dyn Array, out: &mut Vec>) -> PyResult { + let py = self.py; + match array.data_type() { + // A NullArray has no validity buffer; every slot is null. + DataType::Null => { + out.extend((0..array.len()).map(|_| self.none.clone())); + Ok(true) + } + DataType::Boolean => { + let a = array.as_boolean(); + self.each(a, out, |i| { + Ok(Some(PyBool::new(py, a.value(i)).to_owned().into_any())) + }) + } + DataType::Int8 => ints!(self, array, out, Int8Type), + DataType::Int16 => ints!(self, array, out, Int16Type), + DataType::Int32 => ints!(self, array, out, Int32Type), + DataType::Int64 => ints!(self, array, out, Int64Type), + DataType::UInt8 => ints!(self, array, out, UInt8Type), + DataType::UInt16 => ints!(self, array, out, UInt16Type), + DataType::UInt32 => ints!(self, array, out, UInt32Type), + DataType::UInt64 => ints!(self, array, out, UInt64Type), + DataType::Float32 => { + let a = array.as_primitive::(); + self.floats(a, out, |i| f64::from(a.value(i))) + } + DataType::Float64 => { + let a = array.as_primitive::(); + self.floats(a, out, |i| a.value(i)) + } + DataType::Utf8 => { + let a = array.as_string::(); + self.each(a, out, |i| { + Ok(Some(PyString::new(py, a.value(i)).into_any())) + }) + } + DataType::LargeUtf8 => { + let a = array.as_string::(); + self.each(a, out, |i| { + Ok(Some(PyString::new(py, a.value(i)).into_any())) + }) + } + DataType::Binary => { + let a = array.as_binary::(); + self.each(a, out, |i| { + Ok(Some(PyBytes::new(py, a.value(i)).into_any())) + }) + } + DataType::LargeBinary => { + let a = array.as_binary::(); + self.each(a, out, |i| { + Ok(Some(PyBytes::new(py, a.value(i)).into_any())) + }) + } + DataType::FixedSizeBinary(_) => { + let a = array.as_fixed_size_binary(); + self.each(a, out, |i| { + Ok(Some(PyBytes::new(py, a.value(i)).into_any())) + }) + } + DataType::Decimal128(_, scale) => { + let a = array.as_primitive::(); + self.decimals(a, *scale, out) + } + DataType::Decimal256(_, scale) => { + let a = array.as_primitive::(); + self.decimals(a, *scale, out) + } + DataType::Date32 => { + let a = array.as_primitive::(); + let date = cached(py, &DATE, "datetime", &["date"])?; + self.each(a, out, |i| { + let Some((y, m, d)) = ymd(i64::from(a.value(i))) else { + return Ok(None); + }; + Ok(Some(date.call1((y, m, d))?)) + }) + } + DataType::Timestamp(unit, tz) => { + let (values, micros_per_unit): (&[i64], i64) = match unit { + TimeUnit::Second => ( + array.as_primitive::().values(), + MICROS_PER_SECOND, + ), + TimeUnit::Millisecond => ( + array.as_primitive::().values(), + 1_000, + ), + TimeUnit::Microsecond => { + (array.as_primitive::().values(), 1) + } + TimeUnit::Nanosecond => return Ok(false), + }; + self.timestamps(array, values, micros_per_unit, tz.as_deref(), out) + } + _ => Ok(false), + } + } + + /// Append `value(i)` for each valid slot of `array` and `None` for each + /// null; `false` (and stop) as soon as `value` declines a slot. + fn each( + &self, + array: &dyn Array, + out: &mut Vec>, + mut value: impl FnMut(usize) -> PyResult>>, + ) -> PyResult { + for i in 0..array.len() { + if array.is_null(i) { + out.push(self.none.clone()); + continue; + } + match value(i) { + Ok(Some(v)) => out.push(v), + // A failed Python constructor (e.g. a value out of range) is + // left for the caller's fallback to report as it does today. + Ok(None) | Err(_) => return Ok(false), + } + } + Ok(true) + } + + fn floats( + &self, + array: &PrimitiveArray, + out: &mut Vec>, + value: impl Fn(usize) -> f64, + ) -> PyResult { + let py = self.py; + let nan_ok = self.nan_ok; + self.each(array, out, |i| { + let v = value(i); + if v.is_nan() && !nan_ok { + return Ok(None); + } + Ok(Some(PyFloat::new(py, v).into_any())) + }) + } + + /// `decimal.Decimal` from `E<-scale>`, which carries the same + /// digits and exponent as the string pyarrow builds it from. + fn decimals( + &self, + array: &PrimitiveArray, + scale: i8, + out: &mut Vec>, + ) -> PyResult + where + T: ArrowPrimitiveType, + T::Native: std::fmt::Display, + { + let decimal = cached(self.py, &DECIMAL, "decimal", &["Decimal"])?; + let exponent = -i32::from(scale); + self.each(array, out, |i| { + Ok(Some(decimal.call1((format!( + "{}E{}", + array.value(i), + exponent + ),))?)) + }) + } + + /// Like pyarrow: a naive `datetime` for a timestamp without a time zone; + /// otherwise the UTC instant converted with `astimezone` to the zone + /// pyarrow's `string_to_tzinfo` returns for its name. + fn timestamps( + &self, + array: &dyn Array, + values: &[i64], + micros_per_unit: i64, + tz: Option<&str>, + out: &mut Vec>, + ) -> PyResult { + let py = self.py; + let datetime = cached(py, &DATETIME, "datetime", &["datetime"])?; + let zone = match tz { + None => None, + Some(name) => { + let Ok(to_tzinfo) = + cached(py, &STRING_TO_TZINFO, "pyarrow.lib", &["string_to_tzinfo"]) + else { + return Ok(false); + }; + let Ok(zone) = to_tzinfo.call1((name,)) else { + return Ok(false); + }; + Some((zone, cached(py, &UTC, "datetime", &["timezone", "utc"])?)) + } + }; + for (i, &value) in values.iter().enumerate() { + if array.is_null(i) { + out.push(self.none.clone()); + continue; + } + let Some(micros) = value.checked_mul(micros_per_unit) else { + return Ok(false); + }; + let seconds = micros.div_euclid(MICROS_PER_SECOND); + let micro = micros.rem_euclid(MICROS_PER_SECOND); + let second_of_day = seconds.rem_euclid(SECONDS_PER_DAY); + let Some((y, mo, d)) = ymd(seconds.div_euclid(SECONDS_PER_DAY)) else { + return Ok(false); + }; + let (h, mi, s) = ( + second_of_day / 3600, + second_of_day % 3600 / 60, + second_of_day % 60, + ); + let converted = match &zone { + None => datetime.call1((y, mo, d, h, mi, s, micro)), + Some((zone, utc)) => datetime + .call1((y, mo, d, h, mi, s, micro, utc)) + .and_then(|dt| dt.call_method1("astimezone", (zone,))), + }; + match converted { + Ok(v) => out.push(v), + Err(_) => return Ok(false), + } + } + Ok(true) + } +} + +/// Hashable stand-in for a result schema, equal to another key exactly when +/// the schemas are equal (field names, types, nullability and metadata). +/// Lets callers cache what they derive from a schema without converting it +/// to pyarrow, whose `Schema.equals(check_metadata=True)` fingerprints both +/// sides on every call. +#[pyclass(name = "SchemaKey", module = "databricks_sql_kernel", frozen)] +pub(crate) struct SchemaKey { + schema: Arc, + /// Computed on first `hash()`: comparing two keys doesn't need it. + hash: OnceLock, +} + +impl SchemaKey { + pub(crate) fn new(schema: Arc) -> Self { + Self { + schema, + hash: OnceLock::new(), + } + } +} + +#[pymethods] +impl SchemaKey { + /// The key of a `pyarrow.Schema`. + #[new] + fn py_new(schema: &Bound<'_, PyAny>) -> PyResult { + use arrow_pyarrow::FromPyArrow; + Ok(Self::new(Arc::new(Schema::from_pyarrow_bound(schema)?))) + } + + fn __hash__(&self) -> u64 { + *self.hash.get_or_init(|| { + let mut hasher = DefaultHasher::new(); + self.schema.hash(&mut hasher); + hasher.finish() + }) + } + + fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool { + other.cast::().is_ok_and(|other| { + let other = other.get(); + Arc::ptr_eq(&self.schema, &other.schema) || self.schema == other.schema + }) + } + + fn __repr__(&self) -> String { + let names: Vec<&str> = self + .schema + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect(); + format!("SchemaKey({names:?})") + } +} + +/// The rows of pyarrow record batches as `fetch_all_rows` would return them, +/// for testing the conversion against pyarrow's own. `None` where +/// `fetch_all_rows` would decline. Not part of the public API. +#[pyfunction] +#[pyo3(name = "_rows_from_arrow", signature = (batches, nan_ok = false))] +pub(crate) fn rows_from_arrow<'py>( + py: Python<'py>, + batches: Vec>, + nan_ok: bool, +) -> PyResult>> { + use arrow_pyarrow::FromPyArrow; + let batches = batches + .iter() + .map(RecordBatch::from_pyarrow_bound) + .collect::>>()?; + let Some(first) = batches.first() else { + return Ok(Some(PyList::empty(py))); + }; + let schema = first.schema(); + if !schema_is_supported(&schema) { + return Ok(None); + } + rows_to_py(py, &schema, &batches, nan_ok) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{ArrayRef, Date32Array, Float64Array, Int32Array, StringArray}; + use arrow_schema::Field; + + fn batch(columns: Vec<(&str, ArrayRef)>) -> RecordBatch { + RecordBatch::try_from_iter(columns).unwrap() + } + + fn repr(rows: Option>) -> Option { + rows.map(|r| r.repr().unwrap().to_string()) + } + + #[test] + fn ymd_covers_python_date_range_only() { + assert_eq!(ymd(0), Some((1970, 1, 1))); + assert_eq!(ymd(-719_162), Some((1, 1, 1))); + assert_eq!(ymd(2_932_896), Some((9999, 12, 31))); + assert_eq!(ymd(-719_163), None); + assert_eq!(ymd(2_932_897), None); + assert_eq!(ymd(i64::MAX), None); + } + + #[test] + fn rows_are_tuples_with_none_for_nulls() { + Python::initialize(); + Python::attach(|py| { + let b = batch(vec![ + ( + "n", + Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef, + ), + ("s", Arc::new(StringArray::from(vec![Some("a"), None]))), + ]); + let rows = rows_to_py(py, &b.schema(), &[b.clone(), b.slice(1, 1)], false); + assert_eq!( + repr(rows.unwrap()).as_deref(), + Some("[(1, 'a'), (None, None), (None, None)]") + ); + }); + } + + #[test] + fn unconvertible_values_and_mismatched_batches_decline() { + Python::initialize(); + Python::attach(|py| { + let nan = batch(vec![( + "f", + Arc::new(Float64Array::from(vec![f64::NAN])) as ArrayRef, + )]); + let nans = std::slice::from_ref(&nan); + assert!(rows_to_py(py, &nan.schema(), nans, false) + .unwrap() + .is_none()); + assert_eq!( + repr(rows_to_py(py, &nan.schema(), nans, true).unwrap()).as_deref(), + Some("[(nan,)]") + ); + let late = batch(vec![( + "d", + Arc::new(Date32Array::from(vec![2_932_897])) as ArrayRef, + )]); + assert!(rows_to_py(py, &late.schema(), &[late], false) + .unwrap() + .is_none()); + let other = Schema::new(vec![Field::new("f", DataType::Float32, true)]); + assert!(rows_to_py(py, &other, &[nan], true).unwrap().is_none()); + }); + } + + #[test] + fn take_rows_leaves_batches_it_does_not_convert() { + Python::initialize(); + Python::attach(|py| { + let b = batch(vec![( + "n", + Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef, + )]); + let schema = b.schema(); + let mut pending = VecDeque::from([b.clone()]); + // Stream not ended, or more rows than allowed: nothing taken. + assert!(take_rows(py, &schema, false, &mut pending, 10, false) + .unwrap() + .is_none()); + assert!(take_rows(py, &schema, true, &mut pending, 2, false) + .unwrap() + .is_none()); + assert_eq!(pending.len(), 1); + let rows = take_rows(py, &schema, true, &mut pending, 3, false).unwrap(); + assert_eq!(repr(rows).as_deref(), Some("[(1,), (2,), (3,)]")); + assert!(pending.is_empty()); + // An empty, ended stream is zero rows. + let rows = take_rows(py, &schema, true, &mut pending, 0, false).unwrap(); + assert_eq!(repr(rows).as_deref(), Some("[]")); + }); + } + + #[test] + fn schema_keys_compare_schemas_including_metadata() { + let field = Field::new("n", DataType::Int32, true); + let with_meta = field + .clone() + .with_metadata([("databricks.type_name".to_string(), "INT".to_string())].into()); + let key = |f: &Field| SchemaKey::new(Arc::new(Schema::new(vec![f.clone()]))); + let same = |a: &SchemaKey, b: &SchemaKey| a.schema == b.schema; + assert!(same(&key(&with_meta), &key(&with_meta))); + assert!(!same(&key(&with_meta), &key(&field))); + assert!(!same(&key(&field), &key(&field.clone().with_name("m")))); + assert!(!same( + &key(&field), + &key(&field.clone().with_nullable(false)) + )); + assert_eq!(key(&with_meta).__hash__(), key(&with_meta).__hash__()); + } +} diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7f2dc3e8..cb026c38 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -23,7 +23,9 @@ use crate::errors::to_py_err; use crate::executed_async::ExecutedAsyncStatement; use crate::fetch; use crate::params::parse_typed_value; +use crate::rows::{self, SchemaKey}; use crate::runtime::KernelRuntime; +use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ @@ -31,7 +33,8 @@ use databricks_sql_kernel::{ Statement as KStatement, StatementCanceller as KStatementCanceller, }; use pyo3::prelude::*; -use std::collections::HashMap; +use pyo3::types::PyList; +use std::collections::{HashMap, VecDeque}; use std::sync::Arc; /// Python-facing mutable statement. @@ -293,12 +296,17 @@ pub(crate) struct ExecutedStatement { /// survives `close()`, like `statement_id` / `schema`. The connector /// surfaces this as `cursor.rowcount`. num_modified_rows: Option, + /// Whether `fetch_all_rows` converts every column type of `schema`. + rows_supported: bool, } struct ExecutedInner { exec: KExecutedStatement, runtime: Arc, exhausted: bool, + /// Batches `fetch_all_rows` pulled but didn't convert; served first by + /// the Arrow fetches. + pending: VecDeque, } impl ExecutedStatement { @@ -308,12 +316,14 @@ impl ExecutedStatement { let num_modified_rows = exec.num_modified_rows(); Self { statement_id, + rows_supported: rows::schema_is_supported(&schema), schema, num_modified_rows, inner: Some(ExecutedInner { exec, runtime, exhausted: false, + pending: VecDeque::new(), }), } } @@ -341,10 +351,53 @@ impl ExecutedStatement { self.schema.as_ref().to_pyarrow(py) } + /// A `SchemaKey` equal to another statement's when their result schemas + /// are equal, for caching what is derived from a schema without + /// building a `pyarrow.Schema`. Available even after `close()`. + fn schema_key(&self) -> SchemaKey { + SchemaKey::new(self.schema.clone()) + } + + /// All remaining rows as a list of tuples of Python values, if there + /// are at most `max_rows` of them and every column has a type converted + /// here; otherwise `None`, and the next Arrow fetch returns the batches + /// this call pulled. Values are what pyarrow's `to_pylist()` returns. + /// NaN floats return `None` unless `nan_ok`. + #[pyo3(signature = (max_rows, nan_ok = false))] + fn fetch_all_rows<'py>( + &mut self, + py: Python<'py>, + max_rows: usize, + nan_ok: bool, + ) -> PyResult>> { + let inner = alive_mut!(self, "ExecutedStatement"); + if !self.rows_supported { + return Ok(None); + } + if !inner.exhausted { + let runtime = inner.runtime.clone(); + inner.exhausted = run_sync_kernel!( + py, + fetch::fill_exec(&runtime, &mut inner.exec, &mut inner.pending, max_rows) + )?; + } + rows::take_rows( + py, + &self.schema, + inner.exhausted, + &mut inner.pending, + max_rows, + nan_ok, + ) + } + /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` if /// the stream is exhausted. fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { let inner = alive_mut!(self, "ExecutedStatement"); + if let Some(batch) = inner.pending.pop_front() { + return Ok(Some(batch.to_pyarrow(py)?)); + } if inner.exhausted { return Ok(None); } @@ -365,9 +418,15 @@ impl ExecutedStatement { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ExecutedStatement"); - let runtime = inner.runtime.clone(); - let batches = run_sync_kernel!(py, fetch::drain_exec(&runtime, &mut inner.exec))?; - inner.exhausted = true; + let mut batches: Vec = inner.pending.drain(..).collect(); + if !inner.exhausted { + let runtime = inner.runtime.clone(); + batches.extend(run_sync_kernel!( + py, + fetch::drain_exec(&runtime, &mut inner.exec) + )?); + inner.exhausted = true; + } fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/tests/test_rows.py b/pyo3/tests/test_rows.py new file mode 100644 index 00000000..c99a8d78 --- /dev/null +++ b/pyo3/tests/test_rows.py @@ -0,0 +1,287 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Rows as Python values: `fetch_all_rows` returns what pyarrow's +`to_pylist()` returns, and `SchemaKey` compares schemas.""" + +from __future__ import annotations + +import datetime +import random +from decimal import Decimal + +import pyarrow as pa +import pytest + +import databricks_sql_kernel as k + +from conftest import live + +_UTC = datetime.timezone.utc + + +def _converted_columns(): + return { + "i8": pa.array([1, None, -128, 127], pa.int8()), + "i16": pa.array([1, None, -(2**15), 2**15 - 1], pa.int16()), + "i32": pa.array([1, None, -(2**31), 2**31 - 1], pa.int32()), + "i64": pa.array([1, None, -(2**63), 2**63 - 1], pa.int64()), + "u8": pa.array([1, None, 0, 255], pa.uint8()), + "u16": pa.array([1, None, 0, 2**16 - 1], pa.uint16()), + "u32": pa.array([1, None, 0, 2**32 - 1], pa.uint32()), + "u64": pa.array([1, None, 0, 2**64 - 1], pa.uint64()), + "bool": pa.array([True, None, False, True]), + "f32": pa.array([0.1, None, float("inf"), -0.0], pa.float32()), + "f64": pa.array([0.1, None, float("-inf"), -0.0], pa.float64()), + "str": pa.array(["a", None, "", "é\U0001f600"]), + "large_str": pa.array(["a", None, "", "z"], pa.large_string()), + "bin": pa.array([b"a", None, b"", b"\x00\xff"]), + "large_bin": pa.array([b"a", None, b"", b"\x00"], pa.large_binary()), + "fixed_bin": pa.array([b"ab", None, b"cd", b"\x00\x00"], pa.binary(2)), + "dec": pa.array( + [Decimal("123141078.2283"), None, Decimal("-0.0001"), Decimal("0.0000")], + pa.decimal128(38, 4), + ), + "dec_max": pa.array( + [Decimal("9" * 38), None, Decimal("-" + "9" * 38), Decimal(0)], + pa.decimal128(38, 0), + ), + "dec_tiny": pa.array( + [Decimal("1E-20"), None, Decimal("-5E-20"), Decimal("0E-20")], + pa.decimal128(38, 20), + ), + "dec_neg_scale": pa.array( + [Decimal("1.23E+4"), None, Decimal("-1E+2"), Decimal("0E+2")], + pa.decimal128(5, -2), + ), + "dec256": pa.array( + [Decimal("1.5"), None, Decimal("-2.5"), Decimal("1" + "0" * 70 + ".5")], + pa.decimal256(76, 1), + ), + "date": pa.array( + [ + datetime.date(2024, 2, 29), + None, + datetime.date(1, 1, 1), + datetime.date(9999, 12, 31), + ] + ), + "ts": pa.array( + [ + datetime.datetime(2024, 1, 1, 1, 2, 3, 4), + None, + datetime.datetime(1, 1, 1), + datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), + ], + pa.timestamp("us"), + ), + "ts_before_epoch": pa.array([-1, None, -86_400_000_001, -999_999], pa.timestamp("us")), + "ts_s": pa.array([0, None, -1, 253_402_300_799], pa.timestamp("s")), + "ts_ms": pa.array([0, None, -1, 1_710_064_800_123], pa.timestamp("ms")), + "ts_utc": pa.array( + [ + datetime.datetime(2024, 1, 1, tzinfo=_UTC), + None, + datetime.datetime(1, 1, 1, tzinfo=_UTC), + datetime.datetime(2024, 3, 10, 10, tzinfo=_UTC), + ], + pa.timestamp("us", tz="Etc/UTC"), + ), + # The instants DST starts and ends (the latter is ambiguous locally). + "ts_la": pa.array( + [0, None, 1_710_064_800_000_000, 1_699_174_800_000_000], + pa.timestamp("us", tz="America/Los_Angeles"), + ), + "ts_offset": pa.array([0, None, 1, 2], pa.timestamp("ms", tz="+05:30")), + "null": pa.nulls(4), + } + + +def _assert_same(got, expected): + assert len(got) == len(expected) + for row, expected_row in zip(got, expected): + assert type(row) is tuple and len(row) == len(expected_row) + for value, expected_value in zip(row, expected_row): + assert type(value) is type(expected_value) + assert repr(value) == repr(expected_value) + if isinstance(value, datetime.datetime): + assert type(value.tzinfo) is type(expected_value.tzinfo) + assert value.tzinfo == expected_value.tzinfo + assert value.fold == expected_value.fold + + +def _pylist_rows(batches): + table = pa.Table.from_batches(batches) + return list(zip(*(column.to_pylist() for column in table.columns))) or [] + + +@pytest.mark.parametrize("name", sorted(_converted_columns())) +def test_values_match_to_pylist(name): + column = _converted_columns()[name] + batch = pa.record_batch([column, pa.array(range(len(column)))], names=[name, "k"]) + for batches in ([batch], [batch.slice(0, 1), batch.slice(1)], [batch.slice(0, 0)]): + _assert_same(k._rows_from_arrow(batches), _pylist_rows(batches)) + + +def test_random_values_match_to_pylist(): + rng = random.Random(7) + n = 500 + schema = pa.schema( + [ + ("i", pa.int64()), + ("f", pa.float64()), + ("d", pa.decimal128(18, 6)), + ("dt", pa.date32()), + ("ts", pa.timestamp("us")), + ("tz", pa.timestamp("us", tz="Europe/Berlin")), + ("s", pa.string()), + ] + ) + + def maybe(v): + return None if rng.random() < 0.1 else v + + arrays = [ + pa.array([maybe(rng.randint(-(2**63), 2**63 - 1)) for _ in range(n)], pa.int64()), + pa.array([maybe(rng.uniform(-1e300, 1e300)) for _ in range(n)], pa.float64()), + pa.array( + [maybe(Decimal(rng.randint(-(10**18) + 1, 10**18 - 1)).scaleb(-6)) for _ in range(n)], + pa.decimal128(18, 6), + ), + pa.array([maybe(rng.randint(-719_162, 2_932_896)) for _ in range(n)], pa.date32()), + pa.array( + [maybe(rng.randint(-62_135_596_800_000_000, 253_402_300_799_999_999)) for _ in range(n)], + pa.timestamp("us"), + ), + pa.array( + [maybe(rng.randint(-2_000_000_000_000_000, 4_000_000_000_000_000)) for _ in range(n)], + pa.timestamp("us", tz="Europe/Berlin"), + ), + pa.array([maybe("".join(chr(rng.randint(32, 0x2FFF)) for _ in range(rng.randint(0, 8)))) for _ in range(n)]), + ] + batch = pa.record_batch(arrays, schema=schema) + _assert_same(k._rows_from_arrow([batch]), _pylist_rows([batch])) + + +@pytest.mark.parametrize( + "column", + [ + pa.array([1, None], pa.timestamp("ns")), + pa.array([0], pa.date64()), + pa.array([0], pa.time64("us")), + pa.array([0], pa.duration("us")), + pa.array([[1]], pa.list_(pa.int64())), + pa.array([{"x": 1}], pa.struct([("x", pa.int64())])), + pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int64())), + pa.array(["a"]).dictionary_encode(), + pa.array([pa.MonthDayNano([1, 2, 3])], pa.month_day_nano_interval()), + # Values Python's date / datetime can't hold, where to_pylist() raises. + pa.array([2_932_897], pa.date32()), + pa.array([-719_163], pa.date32()), + pa.array([253_402_300_800_000_000], pa.timestamp("us")), + pa.array([2**62], pa.timestamp("s")), + # Converting to the zone leaves datetime's range. + pa.array([-62_135_596_800_000_000], pa.timestamp("us", tz="America/Los_Angeles")), + pa.array([0], pa.timestamp("us", tz="Not/AZone")), + pa.array([float("nan")]), + pa.array([float("nan")], pa.float32()), + ] + # pyarrow < 16 (Python 3.9) has no view types. + + ([pa.array(["a"], pa.string_view())] if hasattr(pa, "string_view") else []), + ids=str, +) +def test_unconverted_types_and_values_decline(column): + batch = pa.record_batch([pa.array(range(len(column))), column], names=["k", "c"]) + assert k._rows_from_arrow([batch]) is None + + +def test_nan_is_kept_when_allowed(): + batch = pa.record_batch([pa.array([float("nan"), 1.0, None])], names=["f"]) + rows = k._rows_from_arrow([batch], nan_ok=True) + assert [repr(r[0]) for r in rows] == ["nan", "1.0", "None"] + + +def test_schema_keys_are_equal_for_equal_schemas(): + def schema(name="n", type_=pa.int32(), nullable=True, metadata=None): + return pa.schema([pa.field(name, type_, nullable, metadata=metadata)]) + + meta = {"databricks.type_name": "INT"} + a, b = k.SchemaKey(schema(metadata=meta)), k.SchemaKey(schema(metadata=meta)) + assert a == b and hash(a) == hash(b) and len({a, b}) == 1 + for other in ( + schema(), + schema(name="m", metadata=meta), + schema(type_=pa.int64(), metadata=meta), + schema(nullable=False, metadata=meta), + schema(metadata={"databricks.type_name": "LONG"}), + ): + assert a != k.SchemaKey(other) + assert a != object() and a != schema(metadata=meta) + + +@live +def test_fetch_all_rows_returns_small_results_as_rows(session): + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n, 'a' AS s, CAST(1.50 AS DECIMAL(5,2)) AS d") + exec_ = stmt.execute() + try: + assert exec_.schema_key() == exec_.schema_key() + assert exec_.fetch_all_rows(10) == [(1, "a", Decimal("1.50"))] + # Exhausted afterwards, like the Arrow fetches. + assert exec_.fetch_all_rows(10) == [] + assert exec_.fetch_next_batch() is None + finally: + exec_.close() + stmt.close() + + +@live +def test_fetch_all_rows_leaves_larger_results_to_the_arrow_fetches(session): + stmt = session.statement() + stmt.set_sql("SELECT id FROM range(1000)") + exec_ = stmt.execute() + try: + assert exec_.fetch_all_rows(10) is None + ids = [] + while (batch := exec_.fetch_next_batch()) is not None: + ids.extend(batch.column(0).to_pylist()) + assert ids == list(range(1000)) + finally: + exec_.close() + stmt.close() + + +@live +def test_fetch_all_rows_declines_unconverted_types(session): + stmt = session.statement() + stmt.set_sql("SELECT array(1, 2) AS a") + exec_ = stmt.execute() + try: + assert exec_.fetch_all_rows(10) is None + assert exec_.fetch_all_arrow().column(0).to_pylist() == [[1, 2]] + finally: + exec_.close() + stmt.close() + + +@live +def test_result_stream_fetch_all_rows(session): + stream = session.metadata().list_catalogs() + try: + expected = stream.arrow_schema() + rows = stream.fetch_all_rows(100_000) + assert rows is not None and all(len(r) == len(expected) for r in rows) + assert stream.schema_key() == k.SchemaKey(expected) + finally: + stream.close() From 6670a7ac119ca3c1b765ebf238d55040c60c839c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 21:23:48 +0000 Subject: [PATCH 2/7] fix(python): decline rows only on range errors; test the batch hand-off offline Review feedback: the row conversion now declines only on OverflowError / ValueError (a date or datetime out of range) and propagates any other Python error. SchemaKey.__eq__ returns NotImplemented for other types. New offline tests drive fetch_all_rows against a local server, for an ExecutedStatement and a ResultStream: reading to the end, declining at several limits with the batches then returned by fetch_next_batch / fetch_all_arrow, and fetch_all_rows after an Arrow fetch. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/rows.rs | 26 ++++++--- pyo3/tests/test_rows.py | 123 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 9 deletions(-) diff --git a/pyo3/src/rows.rs b/pyo3/src/rows.rs index eba7bdef..125e9eda 100644 --- a/pyo3/src/rows.rs +++ b/pyo3/src/rows.rs @@ -30,6 +30,7 @@ use arrow_array::types::{ use arrow_array::{Array, ArrowPrimitiveType, PrimitiveArray, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{Datelike, NaiveDate}; +use pyo3::exceptions::{PyOverflowError, PyValueError}; use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{PyBool, PyBytes, PyFloat, PyList, PyString, PyTuple}; @@ -317,9 +318,9 @@ impl<'py> Converter<'py> { } match value(i) { Ok(Some(v)) => out.push(v), - // A failed Python constructor (e.g. a value out of range) is - // left for the caller's fallback to report as it does today. - Ok(None) | Err(_) => return Ok(false), + Ok(None) => return Ok(false), + Err(e) if out_of_range(self.py, &e) => return Ok(false), + Err(e) => return Err(e), } } Ok(true) @@ -419,13 +420,21 @@ impl<'py> Converter<'py> { }; match converted { Ok(v) => out.push(v), - Err(_) => return Ok(false), + // E.g. a UTC instant near year 1 shifted into a western zone. + Err(e) if out_of_range(py, &e) => return Ok(false), + Err(e) => return Err(e), } } Ok(true) } } +/// Whether `error` is a `date`/`datetime` range error, which the caller's +/// fallback reports (or handles) as it does without this module. +fn out_of_range(py: Python<'_>, error: &PyErr) -> bool { + error.is_instance_of::(py) || error.is_instance_of::(py) +} + /// Hashable stand-in for a result schema, equal to another key exactly when /// the schemas are equal (field names, types, nullability and metadata). /// Lets callers cache what they derive from a schema without converting it @@ -464,11 +473,10 @@ impl SchemaKey { }) } - fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool { - other.cast::().is_ok_and(|other| { - let other = other.get(); - Arc::ptr_eq(&self.schema, &other.schema) || self.schema == other.schema - }) + /// `NotImplemented` (via the failed extraction) for other types. + fn __eq__(&self, other: &Bound<'_, Self>) -> bool { + let other = other.get(); + Arc::ptr_eq(&self.schema, &other.schema) || self.schema == other.schema } fn __repr__(&self) -> String { diff --git a/pyo3/tests/test_rows.py b/pyo3/tests/test_rows.py index c99a8d78..f119943b 100644 --- a/pyo3/tests/test_rows.py +++ b/pyo3/tests/test_rows.py @@ -17,9 +17,13 @@ from __future__ import annotations +import base64 import datetime +import json import random +import threading from decimal import Decimal +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import pyarrow as pa import pytest @@ -228,6 +232,125 @@ def schema(name="n", type_=pa.int32(), nullable=True, metadata=None): ): assert a != k.SchemaKey(other) assert a != object() and a != schema(metadata=meta) + assert a.__eq__(object()) is NotImplemented + + +@pytest.fixture +def local_session(): + """A session on a local server whose every statement returns one inline + attachment holding three 2-row batches (ids 0-5).""" + schema = pa.schema([("id", pa.int64())]) + buffer = pa.BufferOutputStream() + with pa.ipc.new_stream(buffer, schema) as writer: + for lo in (0, 2, 4): + writer.write_batch(pa.record_batch([pa.array([lo, lo + 1])], schema=schema)) + response = { + "statement_id": "test-statement", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [{"name": "id", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0}], + }, + "total_chunk_count": 1, + "total_row_count": 6, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 6, + "attachment": base64.b64encode(buffer.getvalue()).decode(), + }, + } + + class Handler(BaseHTTPRequestHandler): + def respond(self, body, realtime=False): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + payload = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + if realtime: + self.send_header("x-databricks-rt-session", "true") + self.end_headers() + self.wfile.write(payload) + + def do_POST(self): + if self.path.endswith("/sessions"): + self.respond({"session_id": "test-session"}, realtime=True) + else: + self.respond(response) + + def do_GET(self): + self.respond(response) + + def do_DELETE(self): + self.respond({}) + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + threading.Thread(target=server.serve_forever, daemon=True).start() + session = k.Session( + host=f"http://127.0.0.1:{server.server_port}", + http_path="/sql/1.0/warehouses/test-wh", + access_token="test-token", + telemetry_enabled=False, + ) + try: + yield session + finally: + session.close() + server.shutdown() + + +def _handles(session): + """An ExecutedStatement and a ResultStream for the local statement.""" + stmt = session.statement() + stmt.set_sql("SELECT id FROM range(6)") + yield stmt.execute() + stmt = session.statement() + stmt.set_sql("SELECT id FROM range(6)") + yield stmt.submit().await_result() + + +def _ids(handle): + ids = [] + while (batch := handle.fetch_next_batch()) is not None: + ids.extend(batch.column(0).to_pylist()) + return ids + + +@pytest.mark.parametrize("max_rows", [6, 100]) +def test_fetch_all_rows_reads_to_the_end(local_session, max_rows): + for handle in _handles(local_session): + assert handle.fetch_all_rows(max_rows) == [(i,) for i in range(6)] + assert handle.fetch_all_rows(max_rows) == [] + assert handle.fetch_next_batch() is None + assert handle.fetch_all_arrow().num_rows == 0 + handle.close() + + +@pytest.mark.parametrize("max_rows", [0, 1, 3, 5]) +def test_declined_rows_are_returned_by_the_arrow_fetches(local_session, max_rows): + for handle in _handles(local_session): + assert handle.fetch_all_rows(max_rows) is None + # Asking again doesn't lose or repeat what the first call read. + assert handle.fetch_all_rows(max_rows) is None + assert _ids(handle) == list(range(6)) + handle.close() + for handle in _handles(local_session): + assert handle.fetch_all_rows(max_rows) is None + assert handle.fetch_all_arrow().column(0).to_pylist() == list(range(6)) + handle.close() + + +def test_fetch_all_rows_after_an_arrow_fetch_returns_the_rest(local_session): + for handle in _handles(local_session): + assert handle.fetch_next_batch().column(0).to_pylist() == [0, 1] + assert handle.fetch_all_rows(4) == [(2,), (3,), (4,), (5,)] + handle.close() @live From 2b36bfc1719219ba0359a3a36eebb74e7c61d382 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 21:38:14 +0000 Subject: [PATCH 3/7] fix(python): decline a time zone only for expected lookup errors Review feedback: resolving a timestamp column's zone now declines only when pyarrow can't be imported or doesn't know or can't parse the zone (KeyError from zoneinfo and pytz, ValueError), and propagates any other error. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/rows.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/pyo3/src/rows.rs b/pyo3/src/rows.rs index 125e9eda..b062cec6 100644 --- a/pyo3/src/rows.rs +++ b/pyo3/src/rows.rs @@ -30,7 +30,7 @@ use arrow_array::types::{ use arrow_array::{Array, ArrowPrimitiveType, PrimitiveArray, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{Datelike, NaiveDate}; -use pyo3::exceptions::{PyOverflowError, PyValueError}; +use pyo3::exceptions::{PyImportError, PyKeyError, PyOverflowError, PyValueError}; use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{PyBool, PyBytes, PyFloat, PyList, PyString, PyTuple}; @@ -382,13 +382,23 @@ impl<'py> Converter<'py> { let zone = match tz { None => None, Some(name) => { - let Ok(to_tzinfo) = - cached(py, &STRING_TO_TZINFO, "pyarrow.lib", &["string_to_tzinfo"]) - else { - return Ok(false); - }; - let Ok(zone) = to_tzinfo.call1((name,)) else { - return Ok(false); + // Declined: no pyarrow, or a zone it doesn't know (KeyError + // from zoneinfo and pytz) or can't parse (ValueError). + let to_tzinfo = + match cached(py, &STRING_TO_TZINFO, "pyarrow.lib", &["string_to_tzinfo"]) { + Ok(f) => f, + Err(e) if e.is_instance_of::(py) => return Ok(false), + Err(e) => return Err(e), + }; + let zone = match to_tzinfo.call1((name,)) { + Ok(zone) => zone, + Err(e) + if e.is_instance_of::(py) + || e.is_instance_of::(py) => + { + return Ok(false) + } + Err(e) => return Err(e), }; Some((zone, cached(py, &UTC, "datetime", &["timezone", "utc"])?)) } From b37df7ce183b2ecc46bc81ddcbe5d674921c63db Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 21:46:05 +0000 Subject: [PATCH 4/7] fix(python): keep queued batches when fetch_all_arrow fails to drain Review feedback: fetch_all_arrow moved the batches fetch_all_rows had queued into a local list before draining the stream, so a drain error lost them. They now stay queued until the drain succeeds. Tested with a local server whose second chunk fails. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/result_stream.rs | 9 +++-- pyo3/src/statement.rs | 9 +++-- pyo3/tests/test_rows.py | 72 ++++++++++++++++++++++++++++----------- 3 files changed, 61 insertions(+), 29 deletions(-) diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index b92e6f95..cc3522b8 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -138,15 +138,14 @@ impl ResultStream { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ResultStream"); - let mut batches: Vec = inner.pending.drain(..).collect(); + let mut drained = Vec::new(); if !inner.exhausted { let runtime = inner.runtime.clone(); - batches.extend(run_sync_kernel!( - py, - fetch::drain(&runtime, &mut inner.stream) - )?); + drained = run_sync_kernel!(py, fetch::drain(&runtime, &mut inner.stream))?; inner.exhausted = true; } + // `pending` stays put if the drain fails, for the next fetch. + let batches: Vec = inner.pending.drain(..).chain(drained).collect(); fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index cb026c38..e8784250 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -418,15 +418,14 @@ impl ExecutedStatement { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ExecutedStatement"); - let mut batches: Vec = inner.pending.drain(..).collect(); + let mut drained = Vec::new(); if !inner.exhausted { let runtime = inner.runtime.clone(); - batches.extend(run_sync_kernel!( - py, - fetch::drain_exec(&runtime, &mut inner.exec) - )?); + drained = run_sync_kernel!(py, fetch::drain_exec(&runtime, &mut inner.exec))?; inner.exhausted = true; } + // `pending` stays put if the drain fails, for the next fetch. + let batches: Vec = inner.pending.drain(..).chain(drained).collect(); fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/tests/test_rows.py b/pyo3/tests/test_rows.py index f119943b..5281381c 100644 --- a/pyo3/tests/test_rows.py +++ b/pyo3/tests/test_rows.py @@ -18,6 +18,7 @@ from __future__ import annotations import base64 +import contextlib import datetime import json import random @@ -235,15 +236,28 @@ def schema(name="n", type_=pa.int32(), nullable=True, metadata=None): assert a.__eq__(object()) is NotImplemented -@pytest.fixture -def local_session(): - """A session on a local server whose every statement returns one inline - attachment holding three 2-row batches (ids 0-5).""" +@contextlib.contextmanager +def _local_session(chunks): + """A session on a local server whose every statement returns `chunks` + inline: one list of `id` values per batch, one list of batches per chunk. + A `None` chunk is answered with 404.""" schema = pa.schema([("id", pa.int64())]) - buffer = pa.BufferOutputStream() - with pa.ipc.new_stream(buffer, schema) as writer: - for lo in (0, 2, 4): - writer.write_batch(pa.record_batch([pa.array([lo, lo + 1])], schema=schema)) + + def chunk(index): + buffer = pa.BufferOutputStream() + with pa.ipc.new_stream(buffer, schema) as writer: + for ids in chunks[index] or []: + writer.write_batch(pa.record_batch([pa.array(ids)], schema=schema)) + body = { + "chunk_index": index, + "row_offset": sum(len(ids) for c in chunks[:index] for ids in c or []), + "row_count": sum(len(ids) for ids in chunks[index] or []), + "attachment": base64.b64encode(buffer.getvalue()).decode(), + } + if index + 1 < len(chunks): + body["next_chunk_index"] = index + 1 + return body + response = { "statement_id": "test-statement", "status": {"state": "SUCCEEDED"}, @@ -253,22 +267,17 @@ def local_session(): "column_count": 1, "columns": [{"name": "id", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0}], }, - "total_chunk_count": 1, - "total_row_count": 6, - }, - "result": { - "chunk_index": 0, - "row_offset": 0, - "row_count": 6, - "attachment": base64.b64encode(buffer.getvalue()).decode(), + "total_chunk_count": len(chunks), + "total_row_count": sum(len(ids) for c in chunks for ids in c or []), }, + "result": chunk(0), } class Handler(BaseHTTPRequestHandler): - def respond(self, body, realtime=False): + def respond(self, body, realtime=False, status=200): self.rfile.read(int(self.headers.get("Content-Length", 0))) payload = json.dumps(body).encode() - self.send_response(200) + self.send_response(status) self.send_header("Content-Length", str(len(payload))) if realtime: self.send_header("x-databricks-rt-session", "true") @@ -282,7 +291,14 @@ def do_POST(self): self.respond(response) def do_GET(self): - self.respond(response) + if "/result/chunks/" in self.path: + index = int(self.path.rsplit("/", 1)[1].split("?")[0]) + if chunks[index] is None: + self.respond({"error_code": "NOT_FOUND", "message": "gone"}, status=404) + else: + self.respond(chunk(index)) + else: + self.respond(response) def do_DELETE(self): self.respond({}) @@ -305,6 +321,24 @@ def log_message(self, *_args): server.shutdown() +@pytest.fixture +def local_session(): + """Every statement returns one inline chunk of three 2-row batches.""" + with _local_session([[[0, 1], [2, 3], [4, 5]]]) as session: + yield session + + +def test_a_failed_drain_keeps_the_batches_fetch_all_rows_read(): + with _local_session([[[0, 1], [2, 3]], None]) as session: + for handle in _handles(session): + assert handle.fetch_all_rows(1) is None + with pytest.raises(k.KernelError): + handle.fetch_all_arrow() + first = handle.fetch_next_batch() + assert first is not None and first.column(0).to_pylist() == [0, 1] + handle.close() + + def _handles(session): """An ExecutedStatement and a ResultStream for the local statement.""" stmt = session.statement() From f5477ae322ef565c0e3e8252c8bfc6798adcb2e8 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 21:53:55 +0000 Subject: [PATCH 5/7] perf(python): skip the read in fetch_all_rows when queued rows exceed max_rows Review feedback: a repeat call (or one with a smaller max_rows) released and re-took the GIL only to read nothing; it now declines straight away. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/result_stream.rs | 3 ++- pyo3/src/rows.rs | 6 +++++- pyo3/src/statement.rs | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index cc3522b8..47a813fd 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -97,7 +97,8 @@ impl ResultStream { if !self.rows_supported { return Ok(None); } - if !inner.exhausted { + // No GIL hand-off when an earlier call already read more than fits. + if !inner.exhausted && rows::pending_rows(&inner.pending) <= max_rows { let runtime = inner.runtime.clone(); inner.exhausted = run_sync_kernel!( py, diff --git a/pyo3/src/rows.rs b/pyo3/src/rows.rs index b062cec6..b8051f93 100644 --- a/pyo3/src/rows.rs +++ b/pyo3/src/rows.rs @@ -101,6 +101,10 @@ pub(crate) fn schema_is_supported(schema: &Schema) -> bool { schema.fields().iter().all(|f| is_supported(f.data_type())) } +pub(crate) fn pending_rows(pending: &VecDeque) -> usize { + pending.iter().map(RecordBatch::num_rows).sum() +} + /// The rows in `pending` if the stream `ended` with at most `max_rows` of /// them and they convert, clearing `pending`; otherwise `None`, leaving /// `pending` for the Arrow fetches. @@ -112,7 +116,7 @@ pub(crate) fn take_rows<'py>( max_rows: usize, nan_ok: bool, ) -> PyResult>> { - if !ended || pending.iter().map(RecordBatch::num_rows).sum::() > max_rows { + if !ended || pending_rows(pending) > max_rows { return Ok(None); } let rows = rows_to_py(py, schema, pending.make_contiguous(), nan_ok)?; diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index e8784250..587db222 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -374,7 +374,8 @@ impl ExecutedStatement { if !self.rows_supported { return Ok(None); } - if !inner.exhausted { + // No GIL hand-off when an earlier call already read more than fits. + if !inner.exhausted && rows::pending_rows(&inner.pending) <= max_rows { let runtime = inner.runtime.clone(); inner.exhausted = run_sync_kernel!( py, From 7a6f252eef966d3cb7e68dae2a3918c7d4631612 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 22:11:43 +0000 Subject: [PATCH 6/7] perf(python): resolve each time zone once per fetch_all_rows call Review feedback: a zoned timestamp column looked its zone up again for every batch; the converter now keeps the zones it resolved. The docstring says that only such a column uses pyarrow, and the hand-off tests close the Statements they create. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/rows.rs | 60 +++++++++++++++++++++++++---------------- pyo3/src/statement.rs | 3 ++- pyo3/tests/test_rows.py | 16 ++++++----- 3 files changed, 48 insertions(+), 31 deletions(-) diff --git a/pyo3/src/rows.rs b/pyo3/src/rows.rs index b8051f93..85d57347 100644 --- a/pyo3/src/rows.rs +++ b/pyo3/src/rows.rs @@ -35,7 +35,7 @@ use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{PyBool, PyBytes, PyFloat, PyList, PyString, PyTuple}; use std::collections::hash_map::DefaultHasher; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::hash::{Hash, Hasher}; use std::sync::{Arc, OnceLock}; @@ -185,6 +185,8 @@ struct Converter<'py> { py: Python<'py>, nan_ok: bool, none: Bound<'py, PyAny>, + /// Zones resolved so far, by name. + zones: HashMap>, } /// Python `date` fields for days since the Unix epoch, if in `date`'s range @@ -203,6 +205,7 @@ impl<'py> Converter<'py> { py, nan_ok, none: py.None().into_bound(py), + zones: HashMap::new(), } } @@ -370,11 +373,39 @@ impl<'py> Converter<'py> { }) } + /// The tzinfo pyarrow's `string_to_tzinfo` returns for `name`, looked up + /// once per call. `None` (declined) without pyarrow, or for a zone it + /// doesn't know (KeyError from zoneinfo and pytz) or can't parse + /// (ValueError). + fn zone(&mut self, name: &str) -> PyResult>> { + let py = self.py; + if let Some(zone) = self.zones.get(name) { + return Ok(Some(zone.clone())); + } + let to_tzinfo = match cached(py, &STRING_TO_TZINFO, "pyarrow.lib", &["string_to_tzinfo"]) { + Ok(f) => f, + Err(e) if e.is_instance_of::(py) => return Ok(None), + Err(e) => return Err(e), + }; + match to_tzinfo.call1((name,)) { + Ok(zone) => { + self.zones.insert(name.to_owned(), zone.clone()); + Ok(Some(zone)) + } + Err(e) + if e.is_instance_of::(py) || e.is_instance_of::(py) => + { + Ok(None) + } + Err(e) => Err(e), + } + } + /// Like pyarrow: a naive `datetime` for a timestamp without a time zone; /// otherwise the UTC instant converted with `astimezone` to the zone /// pyarrow's `string_to_tzinfo` returns for its name. fn timestamps( - &self, + &mut self, array: &dyn Array, values: &[i64], micros_per_unit: i64, @@ -385,27 +416,10 @@ impl<'py> Converter<'py> { let datetime = cached(py, &DATETIME, "datetime", &["datetime"])?; let zone = match tz { None => None, - Some(name) => { - // Declined: no pyarrow, or a zone it doesn't know (KeyError - // from zoneinfo and pytz) or can't parse (ValueError). - let to_tzinfo = - match cached(py, &STRING_TO_TZINFO, "pyarrow.lib", &["string_to_tzinfo"]) { - Ok(f) => f, - Err(e) if e.is_instance_of::(py) => return Ok(false), - Err(e) => return Err(e), - }; - let zone = match to_tzinfo.call1((name,)) { - Ok(zone) => zone, - Err(e) - if e.is_instance_of::(py) - || e.is_instance_of::(py) => - { - return Ok(false) - } - Err(e) => return Err(e), - }; - Some((zone, cached(py, &UTC, "datetime", &["timezone", "utc"])?)) - } + Some(name) => match self.zone(name)? { + Some(zone) => Some((zone, cached(py, &UTC, "datetime", &["timezone", "utc"])?)), + None => return Ok(false), + }, }; for (i, &value) in values.iter().enumerate() { if array.is_null(i) { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 587db222..f7d30824 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -362,7 +362,8 @@ impl ExecutedStatement { /// are at most `max_rows` of them and every column has a type converted /// here; otherwise `None`, and the next Arrow fetch returns the batches /// this call pulled. Values are what pyarrow's `to_pylist()` returns. - /// NaN floats return `None` unless `nan_ok`. + /// NaN floats return `None` unless `nan_ok`. Only a time-zone-aware + /// timestamp column uses pyarrow, for its `string_to_tzinfo`. #[pyo3(signature = (max_rows, nan_ok = false))] fn fetch_all_rows<'py>( &mut self, diff --git a/pyo3/tests/test_rows.py b/pyo3/tests/test_rows.py index 5281381c..7e67b1fb 100644 --- a/pyo3/tests/test_rows.py +++ b/pyo3/tests/test_rows.py @@ -340,13 +340,15 @@ def test_a_failed_drain_keeps_the_batches_fetch_all_rows_read(): def _handles(session): - """An ExecutedStatement and a ResultStream for the local statement.""" - stmt = session.statement() - stmt.set_sql("SELECT id FROM range(6)") - yield stmt.execute() - stmt = session.statement() - stmt.set_sql("SELECT id FROM range(6)") - yield stmt.submit().await_result() + """An ExecutedStatement and a ResultStream for the local statement; each + Statement is closed once the caller moves on to the next handle.""" + for submit in (False, True): + stmt = session.statement() + stmt.set_sql("SELECT id FROM range(6)") + try: + yield stmt.submit().await_result() if submit else stmt.execute() + finally: + stmt.close() def _ids(handle): From 5e59fbdb917262a10f853906c3c92255e3b14952 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 22:19:22 +0000 Subject: [PATCH 7/7] fix(python): keep every batch a failed fetch_all_arrow read; reject negative max_rows Review feedback: fetch_all_arrow now reads through the pending queue (fill to the end), so a failed read keeps the batches it had already read for the next fetch instead of dropping them; the now-unused drain helpers are removed. fetch_all_rows takes max_rows as an int and raises KernelError (InvalidArgument) for a negative one instead of a PyO3 OverflowError. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/fetch.rs | 44 ++------------------------------------- pyo3/src/macros.rs | 2 +- pyo3/src/result_stream.rs | 14 +++++++------ pyo3/src/rows.rs | 11 ++++++++++ pyo3/src/statement.rs | 14 +++++++------ pyo3/tests/test_rows.py | 18 +++++++++++++--- 6 files changed, 45 insertions(+), 58 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 8f30bcc8..81b1d8c3 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -48,24 +48,6 @@ pub(crate) fn next_batch( }) } -/// Drain the kernel stream and collect every remaining batch. -pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result> { - runtime.block_on(async { - let mut out = Vec::new(); - loop { - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), - Some(_) => { - return Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")); - } - None => break, - } - } - Ok(out) - }) -} - /// Like [`next_batch`], but drives the `ExecutedStatement` (not a bare /// `ResultStream`) so the kernel's auto-close-on-drain fires when the /// stream is exhausted. Used by `ExecutedStatement.fetch_next_batch`. @@ -83,31 +65,9 @@ pub(crate) fn next_batch_exec( }) } -/// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on- -/// drain fires once the stream is exhausted. Used by -/// `ExecutedStatement.fetch_all_arrow`. -pub(crate) fn drain_exec( - runtime: &Runtime, - exec: &mut ExecutedStatement, -) -> Result> { - runtime.block_on(async { - let mut out = Vec::new(); - loop { - match exec.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), - Some(_) => { - return Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")); - } - None => break, - } - } - Ok(out) - }) -} - /// Pull batches into `pending` until it holds more than `max_rows` rows or -/// the stream ends. Returns whether the stream ended. +/// the stream ends (`usize::MAX`: to the end). Returns whether the stream +/// ended. A failed read leaves every batch read so far in `pending`. pub(crate) fn fill( runtime: &Runtime, stream: &mut ResultStream, diff --git a/pyo3/src/macros.rs b/pyo3/src/macros.rs index 9eb9b740..5d223e10 100644 --- a/pyo3/src/macros.rs +++ b/pyo3/src/macros.rs @@ -119,7 +119,7 @@ macro_rules! run_kernel_block { }}; } -/// Run a synchronous helper (e.g. `fetch::next_batch` / `fetch::drain`, +/// Run a synchronous helper (e.g. `fetch::next_batch` / `fetch::fill`, /// which `block_on` internally) with the GIL released, mapping kernel /// errors into `KernelError`. /// diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 47a813fd..47904fa0 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -90,9 +90,10 @@ impl ResultStream { fn fetch_all_rows<'py>( &mut self, py: Python<'py>, - max_rows: usize, + max_rows: i64, nan_ok: bool, ) -> PyResult>> { + let max_rows = rows::max_rows(py, max_rows)?; let inner = alive_mut!(self, "ResultStream"); if !self.rows_supported { return Ok(None); @@ -139,14 +140,15 @@ impl ResultStream { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ResultStream"); - let mut drained = Vec::new(); if !inner.exhausted { let runtime = inner.runtime.clone(); - drained = run_sync_kernel!(py, fetch::drain(&runtime, &mut inner.stream))?; - inner.exhausted = true; + // Read through `pending`, so a failed read loses no batch. + inner.exhausted = run_sync_kernel!( + py, + fetch::fill(&runtime, &mut inner.stream, &mut inner.pending, usize::MAX) + )?; } - // `pending` stays put if the drain fails, for the next fetch. - let batches: Vec = inner.pending.drain(..).chain(drained).collect(); + let batches: Vec = inner.pending.drain(..).collect(); fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/src/rows.rs b/pyo3/src/rows.rs index 85d57347..87556215 100644 --- a/pyo3/src/rows.rs +++ b/pyo3/src/rows.rs @@ -101,6 +101,17 @@ pub(crate) fn schema_is_supported(schema: &Schema) -> bool { schema.fields().iter().all(|f| is_supported(f.data_type())) } +/// `fetch_all_rows`'s `max_rows`, rejecting negatives as `KernelError` +/// (a `usize` parameter would raise `OverflowError` instead). +pub(crate) fn max_rows(py: Python<'_>, max_rows: i64) -> PyResult { + usize::try_from(max_rows).map_err(|_| { + crate::errors::to_py_err( + py, + databricks_sql_kernel::Error::invalid_argument().message("max_rows must be >= 0"), + ) + }) +} + pub(crate) fn pending_rows(pending: &VecDeque) -> usize { pending.iter().map(RecordBatch::num_rows).sum() } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index f7d30824..6216afd7 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -368,9 +368,10 @@ impl ExecutedStatement { fn fetch_all_rows<'py>( &mut self, py: Python<'py>, - max_rows: usize, + max_rows: i64, nan_ok: bool, ) -> PyResult>> { + let max_rows = rows::max_rows(py, max_rows)?; let inner = alive_mut!(self, "ExecutedStatement"); if !self.rows_supported { return Ok(None); @@ -420,14 +421,15 @@ impl ExecutedStatement { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = alive_mut!(self, "ExecutedStatement"); - let mut drained = Vec::new(); if !inner.exhausted { let runtime = inner.runtime.clone(); - drained = run_sync_kernel!(py, fetch::drain_exec(&runtime, &mut inner.exec))?; - inner.exhausted = true; + // Read through `pending`, so a failed read loses no batch. + inner.exhausted = run_sync_kernel!( + py, + fetch::fill_exec(&runtime, &mut inner.exec, &mut inner.pending, usize::MAX) + )?; } - // `pending` stays put if the drain fails, for the next fetch. - let batches: Vec = inner.pending.drain(..).chain(drained).collect(); + let batches: Vec = inner.pending.drain(..).collect(); fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/tests/test_rows.py b/pyo3/tests/test_rows.py index 7e67b1fb..4b48b982 100644 --- a/pyo3/tests/test_rows.py +++ b/pyo3/tests/test_rows.py @@ -328,17 +328,29 @@ def local_session(): yield session -def test_a_failed_drain_keeps_the_batches_fetch_all_rows_read(): +def test_a_failed_drain_keeps_every_batch_it_read(): with _local_session([[[0, 1], [2, 3]], None]) as session: for handle in _handles(session): assert handle.fetch_all_rows(1) is None with pytest.raises(k.KernelError): handle.fetch_all_arrow() - first = handle.fetch_next_batch() - assert first is not None and first.column(0).to_pylist() == [0, 1] + # Queued by fetch_all_rows, then read by the failed drain. + for ids in ([0, 1], [2, 3]): + assert handle.fetch_next_batch().column(0).to_pylist() == ids + with pytest.raises(k.KernelError): + handle.fetch_next_batch() handle.close() +def test_negative_max_rows_is_a_kernel_error(local_session): + for handle in _handles(local_session): + with pytest.raises(k.KernelError) as error: + handle.fetch_all_rows(-1) + assert error.value.code == "InvalidArgument" + assert handle.fetch_all_rows(0) is None + handle.close() + + def _handles(session): """An ExecutedStatement and a ResultStream for the local statement; each Statement is closed once the caller moves on to the next handle."""