This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new 60bb98ea [SPARK-61214][CONNECT][RUST] Match named Row inference in
pandas input
60bb98ea is described below
commit 60bb98ea799c5004fd5e2c53fbe98fcb7d12bd94
Author: DB Tsai <[email protected]>
AuthorDate: Mon Nov 9 16:26:00 2026 +0900
[SPARK-61214][CONNECT][RUST] Match named Row inference in pandas input
### What changes were proposed in this pull request?
Adapt Row-containing inferred columns after customized pandas DataFrame
normalization, then use whole-column Arrow conversion to determine their types
and values. Preserve the converted Arrow arrays, resolved column names,
nullability, dictionary inference and conversion-safety settings. Explicit
struct schemas, local-row construction and the fallback without PyArrow retain
their existing behavior.
### Why are the changes needed?
The native normalization path currently infers named `Row` values as
structs. PySpark Connect's Arrow conversion treats them positionally as
sequences, so the clients produce different inferred schemas and mixed-value
conversion errors. The parity ledger records the remaining normalization-hook
and conversion limits.
### Does this PR introduce _any_ user-facing change?
Yes. On the current development branch, a customized pandas frame
containing `Row(a=1, b=2)` in an inferred object column produces
`struct<a:bigint,b:bigint>`. This change produces `array<bigint>` with value
`[1, 2]`, matching PySpark Connect. Nested Rows, numeric and Decimal inference,
short Row values and incompatible mixed values follow the corresponding Arrow
conversion behavior.
### How was this patch tested?
Added and updated tests cover inferred Rows, nested and mixed values,
dictionary inference, conversion-safety settings and error behavior.
- Offline Python suites: **2,682 passed**, including **all 125 required
cases**; **8 inherited live-only tests skipped** because they require
`SPARK_REMOTE`.
- General pandas live regressions: **8/8 passed**. API introspection found
no missing members across the **12 compared classes**; Row has no missing
members and remains a tuple subclass.
- Bounded reference/native conversion observations: **35/35 matched** (20
successful conversions and 15 expected errors). The equality projection
compares logical types, names, nullability, values and errors; recorded raw
Arrow schema/type strings are excluded. The 19 raw Arrow schema-header
differences contain only the top-level internal placeholder name before the
final column alias. These comparisons also exclude raw IPC bytes, chunking and
schema metadata.
- Paired high-level client checks against an actual JVM: **39/39 passed in
each client**, comprising **24 schema/ordered-collection successes and 15
expected conversion errors**. All 39 compared projections match, including full
schema JSON, row field names, ordered values, requested settings and exact
error fields.
- Advisory Clippy: **exit 101**. Focused binding-library lint reached the
final source and emitted **125 errors in unchanged master source**. No
diagnostic overlaps changed source spans, and neither corrected error closure
emitted a diagnostic. This is an attributed failed lint run.
The release Rust library tests, formatting, all integration-test
compilation with and without `wasm-udf`, and native extension build passed. The
final full-patch review reported no remaining actionable source findings.
The official Python suite executed through this patch's Rust transport:
**87 ordinary modules, 2,586 passed and 641 skipped**, with zero unexpected
failures or errors. One catalog test was deselected by the existing environment
manifest and reconfirmed as an expected missing-test-catalog failure by its
drift check. The separate local-cluster/resource phase completed **4 modules,
15 passed and 14 skipped**, with zero unexpected failures or errors. These are
transport results; native in [...]
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: OpenAI Codex
This pull request and its description were written by OpenAI Codex.
Closes #397 from dbtsai/codex/residual-pandas-row-inference-master-0ac7a0f.
Lead-authored-by: DB Tsai <[email protected]>
Co-authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/session.rs | 622 +++++++++++++++++++----
crates/spark-connect/src/session.rs | 6 +-
dev/parity/known-differences.md | 67 ++-
python/pyspark/sql/_pandas_input.py | 191 +++++++
python/tests/_mock_connect_server.py | 30 +-
python/tests/test_dropin_offline.py | 937 ++++++++++++++++++++++++++++++++++-
6 files changed, 1720 insertions(+), 133 deletions(-)
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index d1c963f5..5a1dae0f 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -649,6 +649,95 @@ pub struct PySparkSession {
streams: std::sync::OnceLock<Py<PyStreamingQueryManager>>,
}
+struct PandasArrowColumn {
+ data_type: DataType,
+ arrays: Vec<arrow::array::ArrayRef>,
+ field: arrow::datatypes::Field,
+}
+
+struct PandasDecimalContext<'a> {
+ dtype: &'a str,
+ label: &'a str,
+ safecheck: Option<bool>,
+}
+
+struct PandasArrowSettings {
+ options: spark_connect::ArrowInputOptions,
+ safecheck: bool,
+ infer_dict_as_map: bool,
+}
+
+impl PandasArrowSettings {
+ fn helper_options(&self) -> (&str, bool, bool) {
+ (
+ self.options.timezone().unwrap_or("UTC"),
+ self.options.use_large_var_types() == Some("true"),
+ self.options.timestamp_type() == Some("TIMESTAMP_NTZ"),
+ )
+ }
+
+ fn prepare_table<'py>(
+ &self,
+ helper: &Bound<'py, PyAny>,
+ frame: &Bound<'py, PyAny>,
+ ) -> PyResult<(Bound<'py, PyAny>, Option<Vec<String>>)> {
+ let (timezone, large, timestamp_ntz) = self.helper_options();
+ helper
+ .getattr("prepare_inferred_pandas_table")?
+ .call1((
+ frame,
+ timezone,
+ self.safecheck,
+ large,
+ self.infer_dict_as_map,
+ timestamp_ntz,
+ ))?
+ .extract()
+ }
+
+ fn prepare_row_column<'py>(
+ &self,
+ helper: &Bound<'py, PyAny>,
+ values: &Bound<'py, PyAny>,
+ name: &str,
+ ) -> PyResult<(DataType, Bound<'py, PyAny>)> {
+ let (timezone, large, timestamp_ntz) = self.helper_options();
+ let result = helper
+ .getattr("prepare_inferred_pandas_row_column")?
+ .call1((
+ values,
+ name,
+ timezone,
+ self.safecheck,
+ large,
+ self.infer_dict_as_map,
+ timestamp_ntz,
+ ))?;
+ let (spark_type, table): (Bound<'py, PyAny>, Bound<'py, PyAny>) =
result.extract()?;
+ Ok((crate::types::py_to_data_type(&spark_type)?, table))
+ }
+}
+
+struct PandasRowColumns {
+ columns: Vec<Option<PandasArrowColumn>>,
+ selected: Vec<bool>,
+ errors: Vec<Option<PyErr>>,
+ settings: Option<PandasArrowSettings>,
+ row_count: usize,
+}
+
+impl PandasRowColumns {
+ fn empty(width: usize, row_count: usize) -> Self {
+ Self {
+ columns: (0..width).map(|_| None).collect(),
+ selected: vec![false; width],
+ errors: (0..width).map(|_| None).collect(),
+ settings: None,
+ row_count,
+ }
+ }
+}
+
impl PySparkSession {
pub fn new(session: SparkSession) -> Self {
// The progress of the session, for the progress bars of its
executions, and its
@@ -908,6 +997,8 @@ impl PySparkSession {
///
/// None for a frame that the row path converts: an empty one, a
customized one
/// (`accepts_pandas_frame`), and any without pyarrow, which the row path
does not need.
+ /// Without pyarrow, that path retains native Row struct inference; with
it,
+ /// customized Row columns can use Arrow after the frame's normalization
hooks.
fn create_from_pandas_inferred(
&self,
py: Python<'_>,
@@ -957,25 +1048,9 @@ impl PySparkSession {
if columns.len() < width {
columns.extend((columns.len()..width).map(|i| format!("_{}", i +
1)));
}
- let options = py.detach(||
self.session.arrow_input_options().to_pyerr())?;
- let conf = |key: &'static str| {
- py.detach(|| self.session.conf().get(key))
- .to_pyerr()
- .map(|value| value.as_deref() == Some("true"))
- };
- let safecheck =
conf("spark.sql.execution.pandas.convertToArrowArraySafely")?;
- let infer_dict_as_map =
- names.is_none() &&
conf("spark.sql.execution.pandas.inferPandasDictAsMap")?;
- let result = helper.getattr("prepare_inferred_pandas_table")?.call1((
- data,
- options.timezone().unwrap_or("UTC"),
- safecheck,
- options.use_large_var_types() == Some("true"),
- infer_dict_as_map,
- options.timestamp_type() == Some("TIMESTAMP_NTZ"),
- ))?;
- let table = result.get_item(0)?;
- if let Some(struct_names) =
result.get_item(1)?.extract::<Option<Vec<String>>>()? {
+ let settings = self.pandas_arrow_settings(py, names.is_none())?;
+ let (table, struct_names) = settings.prepare_table(&helper, data)?;
+ if let Some(struct_names) = struct_names {
columns = struct_names;
}
let actual: usize = table.getattr("num_columns")?.extract()?;
@@ -994,7 +1069,7 @@ impl PySparkSession {
let df = py
.detach(|| {
self.session
- .create_dataframe_from_arrow_with_options(batches, None,
&options)
+ .create_dataframe_from_arrow_with_options(batches, None,
&settings.options)
.map_err(Box::new)
})
.to_pyerr()?;
@@ -1085,6 +1160,8 @@ impl PySparkSession {
/// A DataFrame of a pandas DataFrame: its rows as lists with NaN and NaT
as None, typed
/// by the first non-null value of each column, and its column labels, as
strings, or the
/// given names, applied with `toDF`.
+ /// With PyArrow, schema-free columns containing Rows use whole-column
Arrow inference
+ /// and encoding, and the frame is sent through the Arrow importer.
fn create_from_pandas(
&self,
py: Python<'_>,
@@ -1094,6 +1171,7 @@ impl PySparkSession {
// Without a struct schema, PySpark infers the Arrow type of each
column, which has
// no int64 for a Python int beyond the 64-bit range.
let inferred = !matches!(spec, Spec::Struct(_));
+ let infer_dict_as_map_allowed = matches!(spec, Spec::None);
let mut columns = Vec::new();
for label in data.getattr("columns")?.try_iter()? {
columns.push(label?.str()?.extract::<String>()?);
@@ -1151,22 +1229,83 @@ impl PySparkSession {
(None, Some(names)) => names.clone().into(),
(None, None) => Vec::new().into(),
};
- let mut rows: Vec<Row> = Vec::with_capacity(data.len());
+ // Arrow treats Rows in an inferred pandas column as sequences,
without reading
+ // their field names. Adapt only those columns after the frame's
normalization
+ // hooks; explicit schemas and the other native column converters stay
unchanged.
+ let PandasRowColumns {
+ columns: mut row_columns,
+ selected: selected_row_columns,
+ errors: mut column_errors,
+ settings: row_settings,
+ row_count,
+ } = if given.is_none() {
+ self.prepare_pandas_row_columns(
+ py,
+ &data,
+ &row_names,
+ &labels,
+ &dtypes,
+ infer_dict_as_map_allowed,
+ )?
+ } else {
+ PandasRowColumns::empty(row_names.len(), data.len())
+ };
+ let has_row_columns = selected_row_columns.iter().any(|selected|
*selected);
+ let mut rows: Vec<Row> = Vec::with_capacity(row_count);
for row in data.iter() {
+ if has_row_columns && rows.len() >= row_count {
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "normalized pandas row count changed during conversion",
+ ));
+ }
let values = row
.try_iter()?
- .map(|v| {
+ .enumerate()
+ .map(|(column_index, v)| {
let v = v?;
- if inferred {
- if let Ok(i) = v.cast_exact::<pyo3::types::PyInt>() {
- if i.extract::<i64>().is_err() {
- return
Err(pyo3::exceptions::PyOverflowError::new_err(
- "Python int too large to convert to C
long",
- ));
+ if has_row_columns && column_index >= row_names.len() {
+ // Row detection validated plain list widths before
column conversion.
+ // A hook can change a list before traversal discovers
its final width.
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "normalized pandas row width changed during
conversion",
+ ));
+ }
+ if selected_row_columns.get(column_index) == Some(&true) {
+ return Ok(Value::Null);
+ }
+ if
column_errors.get(column_index).is_some_and(Option::is_some) {
+ // Do not run later scalar hooks in an already failing
column.
+ return Ok(Value::Null);
+ }
+ let converted = (|| {
+ if inferred {
+ if let Ok(i) =
v.cast_exact::<pyo3::types::PyInt>() {
+ if i.extract::<i64>().is_err() {
+ return
Err(pyo3::exceptions::PyOverflowError::new_err(
+ "Python int too large to convert to C
long",
+ ));
+ }
}
}
+ py_to_value(&v)
+ })();
+ match converted {
+ Err(error)
+ if has_row_columns
+ &&
error.is_instance_of::<pyo3::exceptions::PyException>(py) =>
+ {
+ // Run native scalar conversion at most once per
cell, then
+ // report errors in column order alongside Arrow
failures.
+ // Decimal typing can still reread the original
Python values.
+ if let Some(slot) =
column_errors.get_mut(column_index) {
+ *slot = Some(error);
+ Ok(Value::Null)
+ } else {
+ Err(error)
+ }
+ }
+ other => other,
}
- py_to_value(&v)
})
.collect::<PyResult<Vec<_>>>()?;
if values.len() != row_names.len() {
@@ -1179,22 +1318,61 @@ impl PySparkSession {
}
rows.push(StructValue::new(row_names.clone(), values).into());
}
+ if has_row_columns && rows.len() != row_count {
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "normalized pandas row count changed during conversion",
+ ));
+ }
+ let converted_row_count = rows.len();
+ // Move the validated rows into columns once. Encoding each native
column at
+ // its field position preserves error priority over failures in later
Row columns.
+ let mut native_columns = if has_row_columns {
+ let mut columns: Vec<Vec<Value>> = (0..row_names.len())
+ .map(|_| Vec::with_capacity(converted_row_count))
+ .collect();
+ for row in std::mem::take(&mut rows) {
+ for (column, value) in
columns.iter_mut().zip(row.into_values()) {
+ column.push(value);
+ }
+ }
+ Some(columns)
+ } else {
+ None
+ };
// A given struct wins; otherwise each field takes the type of its
first non-null
// value (empty input has a struct schema, checked above), but for
these, which are
// typed as Arrow types a pandas column, as PySpark does: a column of
Decimals takes
// the precision and scale of all its values, and a column without
values the type of
- // its dtype.
+ // its dtype. With PyArrow, Row columns already carry whole-column
Arrow types.
+ let mut arrow_columns = Vec::new();
+ let mut arrow_fields = Vec::new();
let fields = match given {
Some(fields) => fields,
None => {
let mut fields: Vec<StructField> =
Vec::with_capacity(row_names.len());
for (i, name) in row_names.iter().enumerate() {
- // As PySpark, whose Arrow conversion of the column fails
for a null map key.
- if rows
- .iter()
- .filter_map(|row| row.get(i))
- .any(has_null_map_key)
+ if let Some(error) = column_errors[i].take() {
+ return Err(error);
+ }
+ if let Some(PandasArrowColumn {
+ data_type,
+ arrays,
+ field: arrow_field,
+ }) = row_columns[i].take()
{
+ fields.push(StructField {
+ name: name.clone(),
+ data_type,
+ nullable: arrow_field.is_nullable(),
+ metadata: Default::default(),
+ });
+ arrow_columns.push(arrays);
+ arrow_fields.push(arrow_field.with_name(name.clone()));
+ continue;
+ }
+ // As PySpark, whose Arrow conversion of the column fails
for a null map key.
+ let cells = || pandas_column_values(&rows,
native_columns.as_deref(), i);
+ if cells().any(has_null_map_key) {
return Err(PyErr::from_value(
py.import("pyspark.errors")?
.getattr("PySparkTypeError")?
@@ -1206,11 +1384,7 @@ impl PySparkSession {
),))?,
));
}
- let first = rows
- .iter()
- .filter_map(|row| row.get(i))
- .find(|value| !matches!(value, Value::Null));
- let cells = || rows.iter().filter_map(|row| row.get(i));
+ let first = cells().find(|value| !matches!(value,
Value::Null));
let data_type = if !cells().any(|v| matches!(v,
Value::Decimal { .. })) {
match first {
Some(value) => {
@@ -1226,7 +1400,7 @@ impl PySparkSession {
}
}
} else if cells().all(|v| matches!(v, Value::Decimal { ..
} | Value::Null)) {
- pandas_decimal_type(&data, &rows, i)?
+ pandas_decimal_type(&data, i, cells())?
} else {
// Decimals with other values, which PySpark's
conversion leaves to
// Arrow: it types the column, takes ints as Decimals
and raises for
@@ -1245,80 +1419,150 @@ impl PySparkSession {
))?;
let (precision, scale, values): (i32, i32,
Vec<Bound<'_, PyAny>>) =
typed.extract()?;
+ if native_columns.is_some() && values.len() !=
converted_row_count {
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "normalized pandas column has an unexpected
row count",
+ ));
+ }
let values = values
.iter()
.map(|v| Ok(py_to_value(v)?))
.collect::<PyResult<Vec<Value>>>()?;
- rows = std::mem::take(&mut rows)
- .into_iter()
- .zip(values)
- .map(|(row, value)| {
- let mut cells = row.into_values();
- cells[i] = value;
- StructValue::new(row_names.clone(),
cells).into()
- })
- .collect();
+ if let Some(columns) = native_columns.as_mut() {
+ columns[i] = values;
+ } else {
+ rows = std::mem::take(&mut rows)
+ .into_iter()
+ .zip(values)
+ .map(|(row, value)| {
+ let mut cells = row.into_values();
+ cells[i] = value;
+ StructValue::new(row_names.clone(),
cells).into()
+ })
+ .collect();
+ }
DataType::Decimal { precision, scale }
};
- fields.push(StructField {
+ let field = StructField {
name: name.clone(),
data_type,
nullable: true,
metadata: Default::default(),
- });
+ };
+ if let Some(columns) = native_columns.as_mut() {
+ self.check_pandas_decimal_column(
+ py,
+ columns[i].iter(),
+ &field,
+ PandasDecimalContext {
+ dtype: dtypes.get(i).map_or("object",
String::as_str),
+ label: labels.get(i).unwrap_or(name),
+ safecheck:
row_settings.as_ref().map(|settings| settings.safecheck),
+ },
+ )?;
+ let column_names: std::sync::Arc<[String]> =
vec![name.clone()].into();
+ let column_rows: Vec<Row> = std::mem::take(&mut
columns[i])
+ .into_iter()
+ .map(|value|
StructValue::new(column_names.clone(), vec![value]).into())
+ .collect();
+ let column_schema = DataType::Struct {
+ fields: vec![field.clone()],
+ };
+ let batch = py
+ .detach(|| {
+ spark_connect::session::rows_to_arrow_batch(
+ &column_rows,
+ &column_schema,
+ )
+ .map_err(Box::new)
+ })
+ .to_pyerr()?;
+ arrow_columns.push(vec![batch.column(0).clone()]);
+ arrow_fields.push(batch.schema().field(0).clone());
+ }
+ fields.push(field);
}
fields
}
};
- // As PySpark's Arrow conversion of a pandas column: a Decimal that
does not fit the
- // precision and scale of its field exactly fails, rather than losing
digits.
- for (i, field) in fields.iter().enumerate() {
- let DataType::Decimal { precision, scale } = field.data_type else {
- continue;
- };
- let fits = |value: &Value| match value {
- Value::Decimal { value, .. } => {
- spark_connect::session::decimal_str_to_unscaled(value,
precision, scale).is_ok()
+ if !has_row_columns {
+ for (i, field) in fields.iter().enumerate() {
+ self.check_pandas_decimal_column(
+ py,
+ rows.iter().filter_map(|row| row.get(i)),
+ field,
+ PandasDecimalContext {
+ dtype: dtypes.get(i).map_or("object", String::as_str),
+ label: labels.get(i).unwrap_or(&field.name),
+ safecheck: None,
+ },
+ )?;
+ }
+ }
+ let schema = DataType::Struct { fields };
+ let df = if has_row_columns {
+ // Columns may have different chunk boundaries. Slice their
buffers at
+ // shared boundaries without copying or narrowing variable-width
arrays.
+ let arrow_schema =
std::sync::Arc::new(arrow::datatypes::Schema::new(arrow_fields));
+ let mut chunks = vec![0usize; arrow_columns.len()];
+ let mut offsets = vec![0usize; arrow_columns.len()];
+ // Use the validated Rust row count, not a list that scalar hooks
may change.
+ let mut remaining = converted_row_count;
+ let mut batches = Vec::new();
+ while remaining > 0 {
+ let mut length = remaining;
+ for (i, column) in arrow_columns.iter().enumerate() {
+ while column
+ .get(chunks[i])
+ .is_some_and(|array| offsets[i] == array.len())
+ {
+ chunks[i] += 1;
+ offsets[i] = 0;
+ }
+ let array = column.get(chunks[i]).ok_or_else(|| {
+ pyo3::exceptions::PyValueError::new_err(
+ "normalized pandas column has an unexpected row
count",
+ )
+ })?;
+ length = length.min(array.len() - offsets[i]);
}
- _ => true,
- };
- if !rows.iter().filter_map(|row| row.get(i)).all(fits) {
- let mut message = format!(
- "Exception thrown when converting pandas.Series ({}) with
name '{}' to Arrow \
- Array (decimal128({precision}, {scale})).",
- dtypes.get(i).map_or("object", String::as_str),
- labels.get(i).unwrap_or(&field.name),
+ let arrays = arrow_columns
+ .iter()
+ .enumerate()
+ .map(|(i, column)| column[chunks[i]].slice(offsets[i],
length))
+ .collect();
+ batches.push(
+
arrow::record_batch::RecordBatch::try_new(arrow_schema.clone(), arrays)
+ .map_err(|error| {
+
pyo3::exceptions::PyValueError::new_err(error.to_string())
+ })?,
);
- // Read only to raise, as the conf changes the message, not
the failure.
- let safecheck = py
- .detach(|| {
- self.session
- .conf()
-
.get("spark.sql.execution.pandas.convertToArrowArraySafely")
- })
- .map_or(true, |value| value.is_none_or(|value| value ==
"true"));
- if safecheck {
- message.push_str(
- " It can be caused by overflows or other unsafe
conversions warned by \
- Arrow. Arrow safe type check can be disabled by using
SQL config \
-
`spark.sql.execution.pandas.convertToArrowArraySafely`.",
- );
+ for offset in &mut offsets {
+ *offset += length;
}
- return Err(PyErr::from_value(
- py.import("pyspark.errors")?
- .getattr("PySparkValueError")?
- .call1((message,))?,
- ));
+ remaining -= length;
}
- }
- let schema = DataType::Struct { fields };
- let df = py
- .detach(|| {
+ let settings = row_settings.ok_or_else(|| {
+ pyo3::exceptions::PyRuntimeError::new_err("missing pandas Row
Arrow options")
+ })?;
+ py.detach(|| {
+ self.session
+ .create_dataframe_from_arrow_with_options(
+ batches,
+ Some(schema),
+ &settings.options,
+ )
+ .map_err(Box::new)
+ })
+ .to_pyerr()?
+ } else {
+ py.detach(|| {
self.session
.create_dataframe(rows, schema)
.map_err(Box::new)
})
- .to_pyerr()?;
+ .to_pyerr()?
+ };
Ok(PyDataFrame::new(match names {
Some(names) if !names.is_empty() => {
df.to_df(names.iter().map(String::as_str).collect())
@@ -1326,6 +1570,172 @@ impl PySparkSession {
_ => df,
}))
}
+
+ fn pandas_arrow_settings(
+ &self,
+ py: Python<'_>,
+ allow_dict_as_map: bool,
+ ) -> PyResult<PandasArrowSettings> {
+ let options = py.detach(||
self.session.arrow_input_options().to_pyerr())?;
+ let conf = |key: &'static str| {
+ py.detach(|| self.session.conf().get(key).map_err(Box::new))
+ .to_pyerr()
+ .map(|value| value.as_deref() == Some("true"))
+ };
+ Ok(PandasArrowSettings {
+ options,
+ safecheck:
conf("spark.sql.execution.pandas.convertToArrowArraySafely")?,
+ infer_dict_as_map: allow_dict_as_map
+ && conf("spark.sql.execution.pandas.inferPandasDictAsMap")?,
+ })
+ }
+
+ /// Prepare only selected Row columns, retaining ordinary failures by
column index.
+ /// Non-Exception control flow propagates immediately, as it does in
Python helpers.
+ fn prepare_pandas_row_columns(
+ &self,
+ py: Python<'_>,
+ data: &Bound<'_, PyList>,
+ row_names: &[String],
+ labels: &[String],
+ dtypes: &[String],
+ allow_dict_as_map: bool,
+ ) -> PyResult<PandasRowColumns> {
+ let mut prepared = PandasRowColumns::empty(row_names.len(),
data.len());
+ // Only a column of Python objects can hold a Row: walk the cells of
those alone,
+ // so that frames of numeric, boolean, string or datetime columns pay
nothing.
+ let candidates: Vec<usize> = (0..row_names.len())
+ .filter(|&i| {
+ matches!(
+ pandas_dtype_type(dtypes.get(i).map_or("object",
String::as_str)),
+ DataType::Null
+ )
+ })
+ .collect();
+ if candidates.is_empty() {
+ return Ok(prepared);
+ }
+ let helper = py.import("pyspark.sql._pandas_input")?;
+ if !helper.getattr("pyarrow_available")?.call0()?.is_truthy()? {
+ return Ok(prepared);
+ }
+ let columns: Vec<(usize, Bound<'_, PyAny>)> = helper
+ .getattr("inferred_pandas_row_columns")?
+ .call1((data, row_names.len(), candidates))?
+ .extract()?;
+ let Some((first_index, _)) = columns.first() else {
+ return Ok(prepared);
+ };
+ for (index, _) in &columns {
+ let selected = prepared.selected.get_mut(*index).ok_or_else(|| {
+ pyo3::exceptions::PyValueError::new_err(
+ "inferred pandas Row column has an unexpected index",
+ )
+ })?;
+ *selected = true;
+ }
+ let settings = match self.pandas_arrow_settings(py, allow_dict_as_map)
{
+ Ok(settings) => settings,
+ Err(error) if
error.is_instance_of::<pyo3::exceptions::PyException>(py) => {
+ prepared.errors[*first_index] = Some(error);
+ return Ok(prepared);
+ }
+ Err(error) => return Err(error),
+ };
+ for (index, values) in columns {
+ let column = (|| -> PyResult<PandasArrowColumn> {
+ if
values.is_instance_of::<pyo3::exceptions::PyBaseException>() {
+ return Err(PyErr::from_value(values));
+ }
+ let (data_type, table) = settings.prepare_row_column(
+ &helper,
+ &values,
+ labels.get(index).unwrap_or(&row_names[index]),
+ )?;
+ let batches = crate::pyarrow_import::table_batches(&table)?;
+ if batches.iter().any(|batch| batch.num_columns() != 1)
+ || batches.iter().map(|batch|
batch.num_rows()).sum::<usize>()
+ != prepared.row_count
+ {
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "inferred pandas Row column has an unexpected shape",
+ ));
+ }
+ let field = batches[0].schema().field(0).clone();
+ Ok(PandasArrowColumn {
+ data_type,
+ arrays: batches
+ .iter()
+ .map(|batch| batch.column(0).clone())
+ .collect(),
+ field,
+ })
+ })();
+ match column {
+ Ok(column) => prepared.columns[index] = Some(column),
+ Err(error) if
error.is_instance_of::<pyo3::exceptions::PyException>(py) => {
+ prepared.errors[index] = Some(error);
+ }
+ Err(error) => return Err(error),
+ }
+ }
+ prepared.settings = Some(settings);
+ Ok(prepared)
+ }
+
+ /// Keep a Decimal column exact, without invoking its original Python
objects again.
+ fn check_pandas_decimal_column<'a>(
+ &self,
+ py: Python<'_>,
+ values: impl IntoIterator<Item = &'a Value>,
+ field: &StructField,
+ context: PandasDecimalContext<'_>,
+ ) -> PyResult<()> {
+ let DataType::Decimal { precision, scale } = field.data_type else {
+ return Ok(());
+ };
+ let fits = |value: &Value| match value {
+ Value::Decimal { value, .. } => {
+ spark_connect::session::decimal_str_to_unscaled(value,
precision, scale).is_ok()
+ }
+ _ => true,
+ };
+ if values.into_iter().all(fits) {
+ return Ok(());
+ }
+ let PandasDecimalContext {
+ dtype,
+ label,
+ safecheck,
+ } = context;
+ let mut message = format!(
+ "Exception thrown when converting pandas.Series ({dtype}) with
name '{label}' to \
+ Arrow Array (decimal128({precision}, {scale}))."
+ );
+ // Row frames reuse the Arrow settings already read for the whole
frame. Other
+ // native frames retain their existing read-on-error behavior and
default.
+ let safecheck = safecheck.unwrap_or_else(|| {
+ py.detach(|| {
+ self.session
+ .conf()
+
.get("spark.sql.execution.pandas.convertToArrowArraySafely")
+ .map_err(Box::new)
+ })
+ .map_or(true, |value| value.is_none_or(|value| value == "true"))
+ });
+ if safecheck {
+ message.push_str(
+ " It can be caused by overflows or other unsafe conversions
warned by Arrow. \
+ Arrow safe type check can be disabled by using SQL config \
+ `spark.sql.execution.pandas.convertToArrowArraySafely`.",
+ );
+ }
+ Err(PyErr::from_value(
+ py.import("pyspark.errors")?
+ .getattr("PySparkValueError")?
+ .call1((message,))?,
+ ))
+ }
}
/// Whether `obj` is an instance of `module.class`, without importing `module`
when it is not
@@ -2632,21 +3042,39 @@ fn pandas_dtype_type(dtype: &str) -> DataType {
}
}
+/// Read one pandas column from either retained rows or the transposed
Row-frame values.
+/// The row vector is empty when columns are present; these views never
overlap.
+fn pandas_column_values<'a>(
+ rows: &'a [Row],
+ columns: Option<&'a [Vec<Value>]>,
+ index: usize,
+) -> impl Iterator<Item = &'a Value> {
+ rows.iter().filter_map(move |row| row.get(index)).chain(
+ columns
+ .into_iter()
+ .flat_map(move |columns| columns[index].iter()),
+ )
+}
+
/// The decimal type of column `i` of pandas rows, as Arrow infers it from all
its Decimals:
/// the most integer digits and the largest scale of the values.
-fn pandas_decimal_type(data: &Bound<'_, PyList>, rows: &[Row], i: usize) ->
PyResult<DataType> {
+fn pandas_decimal_type<'a>(
+ data: &Bound<'_, PyList>,
+ i: usize,
+ converted: impl IntoIterator<Item = &'a Value>,
+) -> PyResult<DataType> {
// The digits and exponent of an exact C Decimal come from the text that
`py_to_value`
// took of it, rather than from `as_tuple()`, which builds a DecimalTuple
of every digit.
// Subclasses and pure-Python Decimals can override either, so keep their
`as_tuple()`.
let (mut integer_digits, mut scale) = (0i64, 0i64);
let c_decimal = crate::infer::c_decimal_type(data.py())?;
- for (row, converted) in data.iter().zip(rows) {
+ for (row, converted) in data.iter().zip(converted) {
let value = row.get_item(i)?;
if value.is_none() {
continue;
}
- let from_text = match converted.get(i) {
- Some(Value::Decimal { value: text, .. })
+ let from_text = match converted {
+ Value::Decimal { value: text, .. }
if crate::infer::is_exact_c_decimal(&value, c_decimal) =>
{
decimal_text_digits(text)
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index 28832f64..23849793 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1263,7 +1263,11 @@ fn row_width_mismatch(row_index: usize, actual: usize,
expected: usize) -> Spark
/// more than the transfer.
const LOCAL_RELATION_SETTINGS_BYTES: usize = 64 << 10;
-fn rows_to_arrow_batch(
+/// Internal binding bridge for encoding already converted local rows. The
Python
+/// binding also uses it for native columns beside imported pandas Arrow
columns.
+/// Not a stable public API.
+#[doc(hidden)]
+pub fn rows_to_arrow_batch(
rows: &[Row],
schema: &DataType,
) -> Result<arrow::record_batch::RecordBatch> {
diff --git a/dev/parity/known-differences.md b/dev/parity/known-differences.md
index 138d8473..26fcd152 100644
--- a/dev/parity/known-differences.md
+++ b/dev/parity/known-differences.md
@@ -12,26 +12,36 @@ difference is intentional or tracked for a fix.
raises PyArrow's `ArrowInvalid`. This client raises `AXIS_LENGTH_MISMATCH`
for both
rather than drop data.
- **NumPy ndarray input** (tracked by SPARK-60772). Not accepted yet.
+- **Customized pandas Row columns without PyArrow** (intentional
optional-dependency
+ fallback). When PyArrow is unavailable, the native row fallback retains its
previous
+ named-Row struct inference; it does not use Arrow's array inference or
mixed-element
+ rejection. Official PySpark requires PyArrow for pandas input. With PyArrow
available,
+ inferred customized pandas columns containing Rows use its whole-column
inference.
+ This fallback covers unavailable modules detected by `pyarrow_available`,
not an
+ installed PyArrow module that fails during import.
- **Nested pandas Decimal inference and failures** (intentional; related
change:
SPARK-60696).
- - **Inferred precision and scale.** On the native row fallback, inferred
nested
- Decimal fields keep precision 38 and the greatest observed scale; PySpark
infers the
- smallest precision that covers the values. Increasing scale can make a
large value
- exceed precision 38 even when the first value's scale could encode every
value by
- discarding only trailing zeros. For example, with `[Decimal("9" * 37 +
".0")]`
- followed by `[Decimal("1.0000000")]`, the first value would need 44 digits
at scale
- 7, beyond precision 38; the previous native fallback accepted both at
scale 1.
- PySpark Connect 4.3.0 constructs a DataFrame for this example, but
requesting its
- schema or collecting results raises `ArithmeticException`
+ - **Inferred precision and scale.** On the native row fallback, inferred
nested Decimal
+ fields in non-Row columns keep precision 38 and the greatest observed
scale; PySpark
+ infers the smallest precision that covers the values. When PyArrow is
available,
+ columns containing Rows follow Arrow's array inference, smallest covering
Decimal
+ precision and incompatible-value errors instead. Without PyArrow, those
columns retain
+ native struct inference and this precision difference. Increasing scale on
the native
+ path can make a large value exceed precision 38 even when the first
value's scale
+ could encode every value by discarding only trailing zeros. For example,
with
+ `[Decimal("9" * 37 + ".0")]` followed by `[Decimal("1.0000000")]`, the
first value
+ would need 44 digits at scale 7, beyond precision 38; the previous native
fallback
+ accepted both at scale 1. PySpark Connect 4.3.0 constructs a DataFrame for
this
+ example, but requesting its schema or collecting results raises
`ArithmeticException`
(`DECIMAL_PRECISION_EXCEEDS_MAX_PRECISION`, precision 44, maximum 38).
This client's
native fallback instead raises `PySparkRuntimeError` during construction,
before
sending a relation. The rejection stage and error class differ.
- **Scale beyond 38.** A later value that increases the scale beyond 38
raises
`ValueError` before upload. This can reject later zero or trailing-zero
values that
- the previous native fallback accepted at the first value's scale. Existing
container
- and non-Decimal inference rules are unchanged.
+ the previous native fallback accepted at the first value's scale. This
scale handling
+ applies to the non-Row columns and no-PyArrow fallback described above.
- **Explicit schema.** With an explicit schema, a nested Decimal that does
not fit
raises `PySparkRuntimeError` only on the native row fallback, for frames
rejected by
@@ -43,6 +53,41 @@ difference is intentional or tracked for a fix.
converts other fields. If an earlier non-Decimal column and a later Decimal
column are
both invalid, this client reports the Decimal column first; PySpark reports
the first
invalid column in schema order. Both reject the input before a relation is
sent.
+- **Hook timing in customized pandas frames containing Rows** (intentional).
With PyArrow
+ available, Row columns are prepared with Arrow before native scalar
conversion.
+ Detection covers direct Row cells and nesting through list, tuple and dict
instances,
+ including subclasses. Other cell containers are not traversed by this
adaptation.
+ Discovery walks those containers with an explicit frame stack in
base-iterator order.
+ Shared acyclic containers are visited at each occurrence. A cycle on the
active path
+ raises `ValueError` with `cyclic container in inferred pandas Row
discovery`, including
+ in Row-free cells. Ordinary discovery errors retain their column index for
deferred
+ error handling and cause the frame to read Arrow settings even if discovery
found no
+ Row. Native and Arrow conversions retain their existing nesting limits.
+ Replacing a nested dict value containing a Row hashes its original key and
may compare
+ keys during lookup. Custom key hooks can therefore run during discovery;
callback
+ counts follow normal Python dict behavior, including collisions.
+ Adapted frames use the Arrow importer's session settings and transport
policy:
+ `spark.sql.session.localRelationCacheThreshold` selects inline data or
cached-artifact
+ upload, with the importer's size and chunk limits. Frames whose discovery
finds neither
+ Rows nor an error retain native conversion and its upstream transport
policy. For native
+ rows, Arrow data below 64 KiB stays inline without that settings RPC; at 64
KiB or more,
+ the upstream path reads the local-relation settings. For adapted frames, a
failure
+ reading the shared settings is reported at the first selected column's
position, so an
+ earlier invalid native column is reported first. Official PySpark reads
configuration
+ before converting any column.
+
+ Other columns run native scalar conversion (`py_to_value`) at most once per
cell.
+ Decimal typing can read original objects again: column typing calls
`as_tuple()` on
+ values other than exact C Decimals, and Arrow rereads columns mixing
Decimals with other
+ values. After an ordinary native scalar-conversion exception, later cells in
that column
+ are not converted. Ordinary failures are retained and checked in column
order alongside
+ inference and encoding, so the earliest invalid column wins. The deferred
error
+ handling retains only Python `Exception` instances; other propagated
exceptions, such
+ as `KeyboardInterrupt` from a Decimal hook, return immediately. On failing
input,
+ callbacks in later columns may already have run, and callbacks in a Row
column may
+ precede those in an earlier native column. Official PySpark converts
complete columns
+ from left to right. The fallback's frame normalization hooks are preserved;
callback
+ timing differs from official PySpark.
- **Decimal context hooks during local-row conversion** (intentional,
SPARK-60704).
Quantum and context objects are shared by Decimal type within one conversion
and built
when its first non-null, non-NaN value is converted. PySpark constructs a
context for
diff --git a/python/pyspark/sql/_pandas_input.py
b/python/pyspark/sql/_pandas_input.py
index 7329ea4c..f177f336 100644
--- a/python/pyspark/sql/_pandas_input.py
+++ b/python/pyspark/sql/_pandas_input.py
@@ -1236,6 +1236,197 @@ def pyarrow_available():
return False
+def inferred_pandas_row_columns(rows, width, candidates=None):
+ """Return inferred columns containing Rows, with their values viewed as
sequences.
+
+ Walk only the columns of the indices ``candidates``, in increasing order,
when
+ given: the caller passes those whose pandas dtype can hold Python objects.
+
+ Present tuple-backed Rows positionally. Keep field metadata out of this
+ conversion, as Arrow does when it infers a column containing tuple Rows.
+ Find Rows directly in cells or nested in list, tuple and dict instances,
including
+ subclasses. Other cell containers are not traversed by this adaptation.
+ Walk iteratively and reject cycles among these containers with ValueError.
Ordinary
+ discovery errors retain their column index, even if that column contains
no Row.
+ Frames have already run the row path's normalization hooks. Inspect only
the plain
+ rows produced by pandas; customized row containers keep their existing
conversion.
+ """
+ from pyspark._pyspark import Row
+
+ unchanged = object()
+
+ class Frame:
+ """One active container; non-Row output is copied only after a changed
child."""
+
+ __slots__ = ("original", "kind", "iterator", "items", "index",
"pending",
+ "key", "pending_value", "next_is_value", "visiting_key",
"key_has_row")
+
+ def __init__(self, original, kind, iterator):
+ self.original = original
+ self.kind = kind
+ self.iterator = iterator
+ self.items = [] if kind == "row" else None
+ self.index = -1
+ self.pending = None
+ self.key = None
+ self.pending_value = None
+ self.next_is_value = False
+ self.visiting_key = False
+ self.key_has_row = False
+
+ def next_child(self):
+ if self.kind == "dict":
+ if self.next_is_value:
+ self.next_is_value = False
+ self.visiting_key = False
+ return self.pending_value
+ self.key, self.pending_value = next(self.iterator)
+ self.next_is_value = True
+ self.visiting_key = True
+ return self.key
+ self.pending = next(self.iterator)
+ self.index += 1
+ return self.pending
+
+ def accept(self, converted):
+ if self.kind == "row":
+ self.items.append(self.pending if converted is unchanged else
converted)
+ elif self.kind == "dict":
+ if self.visiting_key:
+ self.key_has_row = converted is not unchanged
+ elif self.key_has_row or converted is not unchanged:
+ if self.items is None:
+ self.items = dict.copy(self.original)
+ # Keep invalid Row keys intact for Arrow's rejection/cause
wording.
+ if converted is not unchanged:
+ # Replacement hashes the original key and may compare
keys;
+ # callback counts follow normal Python dict behavior.
+ self.items[self.key] = converted
+ elif converted is not unchanged:
+ if self.items is None:
+ # This single shallow copy does not repeat discovery or
scalar hooks.
+ self.items = (list.copy(self.original) if self.kind ==
"list"
+ else list(tuple.__iter__(self.original)))
+ self.items[self.index] = converted
+
+ def finish(self):
+ if self.items is None:
+ return unchanged
+ return tuple(self.items) if self.kind == "row" or self.kind ==
"tuple" else self.items
+
+ def frame_for(value):
+ cls = type(value)
+ # Exact builtin scalars cannot contain Rows. Keep checking every cell:
+ # a later value in the same column may contain a Row at any nesting
depth.
+ # Identity checks avoid invoking a custom metaclass's equality or hash
hooks.
+ if (value is None or cls is bool or cls is int or cls is float
+ or cls is complex or cls is str or cls is bytes or cls is
bytearray):
+ return None
+ if type.__subclasscheck__(Row, cls):
+ return Frame(value, "row", tuple.__iter__(value))
+ if type.__subclasscheck__(list, cls):
+ return Frame(value, "list", list.__iter__(value))
+ if type.__subclasscheck__(tuple, cls):
+ return Frame(value, "tuple", tuple.__iter__(value))
+ if type.__subclasscheck__(dict, cls):
+ return Frame(value, "dict", iter(dict.items(value)))
+ return None
+
+ def scalar(value):
+ cls = type(value)
+ return (value is None or cls is bool or cls is int or cls is float
+ or cls is complex or cls is str or cls is bytes or cls is
bytearray)
+
+ def flat(value):
+ # Exact builtin scalars, and exact lists, tuples and dicts of them,
the most
+ # common cells, cannot hold a Row: skip their walk. Read them with the
same
+ # builtin iterators as the walk, so that no other hook of a cell runs.
+ cls = type(value)
+ if cls is list:
+ return all(map(scalar, list.__iter__(value)))
+ if cls is tuple:
+ return all(map(scalar, tuple.__iter__(value)))
+ if cls is dict:
+ return all(scalar(key) and scalar(item) for key, item in
dict.items(value))
+ return scalar(value)
+
+ def positional(value):
+ if flat(value):
+ return unchanged
+ first = frame_for(value)
+ if first is None:
+ return unchanged
+ stack = [first]
+ # Active IDs detect back edges, not shared acyclic subtrees. Frames
retain
+ # their original objects so these IDs cannot be reused during
traversal.
+ active = {id(value)}
+ while stack:
+ frame = stack[-1]
+ try:
+ child = frame.next_child()
+ except StopIteration:
+ converted = frame.finish()
+ active.remove(id(frame.original))
+ stack.pop()
+ if not stack:
+ return converted
+ stack[-1].accept(converted)
+ continue
+ if id(child) in active:
+ raise ValueError("cyclic container in inferred pandas Row
discovery")
+ nested = frame_for(child)
+ if nested is None:
+ frame.accept(unchanged)
+ else:
+ active.add(id(child))
+ stack.append(nested)
+
+ if any(type(row) is not list or len(row) != width for row in
list.__iter__(rows)):
+ return []
+ columns = []
+ for index in range(width) if candidates is None else candidates:
+ values = None
+ try:
+ for row_index, row in enumerate(list.__iter__(rows)):
+ converted = positional(row[index])
+ if converted is not unchanged:
+ if values is None:
+ values = [item[index] for item in list.__iter__(rows)]
+ values[row_index] = converted
+ except Exception as error:
+ # Retain the column index so an earlier native failure still wins.
+ columns.append((index, error))
+ continue
+ if values is not None:
+ columns.append((index, values))
+ return columns
+
+
+def prepare_inferred_pandas_row_column(values, name, timezone, safecheck,
+ prefers_large_types, infer_dict_as_map,
+ prefer_timestamp_ntz):
+ """Infer an adapted Row column with the same whole-column Arrow conversion
as pandas.
+
+ Other columns keep native conversion, including their string and Decimal
hooks.
+ Use the existing pandas helper for recursive inference, mixed-value errors
and the
+ inferPandasDictAsMap option rather than guessing an element type from the
first Row.
+ Return the inferred Spark type and the original one-column Arrow table.
+ """
+ from pandas.core.frame import DataFrame
+ from pyspark.sql.pandas.types import from_arrow_type
+
+ frame = DataFrame({name: values}, dtype=object)
+ table, _ = prepare_inferred_pandas_table(
+ frame, timezone, safecheck, prefers_large_types, infer_dict_as_map,
+ prefer_timestamp_ntz,
+ )
+ # Infer from the resulting Arrow timezone, as the server does: a timestamp
+ # without a timezone is NTZ. Dict-as-map coercion has already applied the
+ # session preference to the Arrow type. Keep the arrays to avoid
re-encoding
+ # naive wall clocks, large variable-width types or nested nullability.
+ return from_arrow_type(table.column(0).type), table
+
+
def prepare_inferred_pandas_table(frame, timezone, safecheck,
prefers_large_types,
infer_dict_as_map, prefer_timestamp_ntz):
"""Convert a pandas frame without a schema, or of names, as PySpark
Connect does.
diff --git a/python/tests/_mock_connect_server.py
b/python/tests/_mock_connect_server.py
index 3e09303e..c2f67b90 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -391,12 +391,14 @@ def serve(connection):
# server does for an error that it raised: INTERNAL, with a
google.rpc.Status of an
# ErrorInfo of `reason` and `metadata` in grpc-status-details-bin.
execute_error = None
- # FetchErrorDetails returns `error_details` (raw
FetchErrorDetailsResponse fields) and
- # records the error id asked for. Config Get returns the values in
`confs`, or else
- # those of `default_confs`, the defaults of SQL configs of the server,
and fails for a
- # key without one, as the server does for an unset config; it records
the keys, as
- # does GetWithDefault, which returns the values in `confs` or else the
defaults that
- # it is given. Config Set records the pairs and the silent flag of
each request.
+ # FetchErrorDetails returns `error_details` (raw
FetchErrorDetailsResponse fields)
+ # and records the error id asked for. Config Get returns the values in
`confs`, or
+ # else those of `default_confs`, the defaults of SQL configs of the
server, and
+ # fails for a key without one, as the server does for an unset config.
A key
+ # stored as None is returned without the optional value. Get records
the keys, as
+ # does GetWithDefault, which returns the values in `confs` or else the
defaults
+ # that it is given. Config Set records the pairs and the silent flag
of each
+ # request.
error_details = b""
fetched_error_ids = []
confs = {}
@@ -692,7 +694,11 @@ def serve(connection):
context.abort(grpc.StatusCode.INTERNAL, "[SQL_CONF_NOT_FOUND]")
# The response names the session, as the server's does.
return message_field(1, request[1][0]) + b"".join(
- message_field(2, message_field(1, key) + message_field(2,
confs[key]))
+ message_field(
+ 2,
+ message_field(1, key)
+ + (b"" if confs[key] is None else message_field(2,
confs[key])),
+ )
for key in keys
)
@@ -728,6 +734,9 @@ def serve(connection):
elif command[0] == "set":
setattr(service, command[1], command[2])
connection.send(None)
+ elif command[0] == "del":
+ delattr(service, command[1])
+ connection.send(None)
elif command[0] == "release":
service.response_gate.set()
connection.send(None)
@@ -782,6 +791,13 @@ class RemoteService:
assert self.connection.poll(10), "Mock server did not respond"
self.connection.recv()
+ def __delattr__(self, name):
+ # pytest 9's monkeypatch undoes an attribute that the instance did not
hold with
+ # delattr, which removes the override of the service's class attribute.
+ self.connection.send(("del", name))
+ assert self.connection.poll(10), "Mock server did not respond"
+ self.connection.recv()
+
def release_response(self):
self.connection.send(("release",))
assert self.connection.poll(10), "Mock server did not respond"
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 46165f8a..2eb7c42c 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -8082,6 +8082,827 @@ def _native_number_input_table(mock_connect, data,
schema=None, *, source="local
return pa.ipc.open_stream(local[1][0]).read_all()
[email protected]("schema", [None, ["renamed"]])
[email protected]("values, expected", [
+ ([Row()], [[]]),
+ ([Row(a=1, b=2), None, Row(a=3, b=None)], [[1, 2], None, [3, None]]),
+ ([Row("a", "b")(1), Row("a", "b")(2)], [[1], [2]]),
+ ([Row(a=None, b=None), Row(a=1, b=2)], [[None, None], [1, 2]]),
+ ([Row(a=1, b=2), Row(a=1.5, b=2.5)], [[1.0, 2.0], [1.5, 2.5]]),
+ ([Row(a=Row(x=1, y=2), b=Row(x=3, y=None))], [[[1, 2], [3, None]]]),
+ ([[Row(x=1, y=2), Row(x=3, y=4)]], [[[1, 2], [3, 4]]]),
+ ([{"child": Row(x=1, y=2)}], [{"child": [1, 2]}]),
+])
+def test_customized_pandas_named_rows_are_inferred_as_arrays(
+ mock_connect, schema, values, expected
+):
+ # Official pandas inference sends the whole object column to Arrow without
a Spark
+ # type. Row field names do not participate, including for nested and short
Rows.
+ import pyarrow as pa
+
+ pd = pytest.importorskip("pandas")
+ frame = _RowPathFrame(pd)({"value": values}, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame,
schema).column(0).combine_chunks()
+ wanted = pa.array(expected, from_pandas=True)
+ assert actual.equals(wanted)
+
+
[email protected]("schema", [None, ["renamed"]])
[email protected]("values", [
+ [Row(a=1, b="x")],
+ [Row(a=1, b=2), Row(a=3, b="x")],
+ [[Row(a=1, b="x")]],
+ [Row(a=1), {"a": 2}],
+])
+def test_customized_pandas_mixed_named_rows_raise_arrow_errors(mock_connect,
schema, values):
+ from pyspark.errors import PySparkValueError
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ frame = _RowPathFrame(pd)({"value": values}, dtype=object)
+ before = len(service.execute_requests)
+ with pytest.raises(PySparkValueError, match=r"pandas.Series \(object\)
with name 'value'"):
+ spark.createDataFrame(frame, schema)
+ assert len(service.execute_requests) == before
+
+
+def test_customized_pandas_named_row_keys_raise_arrow_errors(mock_connect):
+ from pyspark.errors import PySparkTypeError
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ frame = _RowPathFrame(pd)({"value": [{Row(a=1, b=2): 3}]}, dtype=object)
+ before = len(service.execute_requests)
+ with pytest.raises(PySparkTypeError, match=r"pandas.Series \(object\) with
name 'value'"):
+ spark.createDataFrame(frame)
+ assert len(service.execute_requests) == before
+
+
[email protected]("schema", [None, ["renamed"]])
+def
test_customized_pandas_named_rows_preserve_dict_inference_option(mock_connect,
schema):
+ import pyarrow as pa
+
+ pd = pytest.importorskip("pandas")
+ _, service = mock_connect
+ service.confs = {"spark.sql.execution.pandas.inferPandasDictAsMap": "true"}
+ values = [{"child": Row(a=1, b=2)}, None, {"child": Row(a=3, b=4)}]
+ frame = _RowPathFrame(pd)({"value": values}, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame,
schema).column(0).combine_chunks()
+ if schema is None:
+ expected_type = pa.map_(pa.string(), pa.list_(pa.int64()))
+ expected = [[("child", [1, 2])], None, [("child", [3, 4])]]
+ else:
+ # The option applies only with schema=None, as in official PySpark.
+ expected_type = pa.struct([("child", pa.list_(pa.int64()))])
+ expected = [{"child": [1, 2]}, None, {"child": [3, 4]}]
+ assert actual.equals(pa.array(expected, type=expected_type))
+
+
[email protected]("safecheck", [False, True])
+def
test_customized_pandas_named_row_errors_respect_safecheck_option(mock_connect,
safecheck):
+ from pyspark.errors import PySparkValueError
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ service.confs = {
+ "spark.sql.execution.pandas.convertToArrowArraySafely":
str(safecheck).lower()
+ }
+ frame = _RowPathFrame(pd)({"value": [Row(a=1, b="x")]}, dtype=object)
+ with pytest.raises(PySparkValueError) as error:
+ spark.createDataFrame(frame)
+ expected = (
+ "Exception thrown when converting pandas.Series (object) with name
'value' "
+ "to Arrow Array (None)."
+ )
+ if safecheck:
+ expected += (
+ " It can be caused by overflows or other unsafe conversions warned
by Arrow. "
+ "Arrow safe type check can be disabled by using SQL config "
+ "`spark.sql.execution.pandas.convertToArrowArraySafely`."
+ )
+ assert str(error.value) == expected
+
+
[email protected]("kind", ["row", "native", "native_without_rows"])
+def test_customized_pandas_row_frames_share_absent_safecheck_setting(
+ mock_connect, kind
+):
+ from decimal import Decimal
+ from pyspark.errors import PySparkValueError
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ key = "spark.sql.execution.pandas.convertToArrowArraySafely"
+ # A KeyValue with no optional value is read as None, rather than an RPC
error.
+ service.confs = {key: None}
+
+ class NarrowDecimal(Decimal):
+ def as_tuple(self):
+ # Keep the native Decimal exactness check observable through its
tuple hook.
+ return Decimal("0.0").as_tuple()
+
+ columns = {"native": [Decimal("1.5") if kind == "row" else
NarrowDecimal("1.5")]}
+ if kind != "native_without_rows":
+ columns["rows"] = [Row(a=1, b="x") if kind == "row" else Row(a=1)]
+ frame = _RowPathFrame(pd)(columns, dtype=object)
+ before_reads = service.read_confs.count(key)
+ before_execute = len(service.execute_requests)
+ with pytest.raises(PySparkValueError) as error:
+ spark.createDataFrame(frame)
+ label, arrow_type = ("rows", "None") if kind == "row" else ("native",
"decimal128(1, 1)")
+ expected = (
+ f"Exception thrown when converting pandas.Series (object) with name
'{label}' "
+ f"to Arrow Array ({arrow_type})."
+ )
+ if kind == "native_without_rows":
+ # Preserve the existing native fallback's default when no Row settings
were read.
+ expected += (
+ " It can be caused by overflows or other unsafe conversions warned
by Arrow. "
+ "Arrow safe type check can be disabled by using SQL config "
+ "`spark.sql.execution.pandas.convertToArrowArraySafely`."
+ )
+ assert str(error.value) == expected
+ assert service.read_confs.count(key) - before_reads == 1
+ assert len(service.execute_requests) == before_execute
+
+
[email protected]("timestamp_type", ["TIMESTAMP_LTZ", "TIMESTAMP_NTZ"])
[email protected]("infer_dict_as_map", [False, True])
[email protected]("aware", [False, True])
+def
test_customized_pandas_named_row_timestamps_preserve_arrow_type_and_wall_clock(
+ mock_connect, monkeypatch, timestamp_type, infer_dict_as_map, aware
+):
+ import pyarrow as pa
+ from datetime import datetime, timezone
+
+ if not hasattr(time, "tzset"):
+ pytest.skip("client timezone control requires time.tzset")
+ pd = pytest.importorskip("pandas")
+ _, service = mock_connect
+ service.confs = {
+ "spark.sql.timestampType": timestamp_type,
+ "spark.sql.execution.pandas.inferPandasDictAsMap":
str(infer_dict_as_map).lower(),
+ }
+ value = datetime(2020, 1, 2, 3, 4, 5, 123456, tzinfo=timezone.utc if aware
else None)
+ frame = _RowPathFrame(pd)({"value": [Row(t=value), None]}, dtype=object)
+ try:
+ with monkeypatch.context() as environment:
+ environment.setenv("TZ", "America/Los_Angeles")
+ time.tzset()
+ actual = _native_number_input_table(mock_connect,
frame).column(0).combine_chunks()
+ finally:
+ time.tzset()
+ # With no coercion, timezone-free Arrow timestamps imply NTZ regardless of
the
+ # session preference. Dict-as-map first casts to the session's Arrow
schema.
+ has_timezone = aware or (infer_dict_as_map and timestamp_type ==
"TIMESTAMP_LTZ")
+ expected_type = pa.list_(pa.timestamp("us", tz="UTC" if has_timezone else
None))
+ expected_value = value.replace(tzinfo=timezone.utc) if has_timezone else
value
+ assert actual.type == expected_type
+ assert actual.to_pylist() == [[expected_value], None]
+
+
[email protected]("kind", ["date", "timedelta"])
+def
test_customized_pandas_named_row_dates_and_timedeltas_keep_arrow_values(mock_connect,
kind):
+ import pyarrow as pa
+ from datetime import date, timedelta
+
+ pd = pytest.importorskip("pandas")
+ values = ([date(1969, 12, 31), date(2000, 2, 29)] if kind == "date"
+ else [timedelta(microseconds=-1), timedelta(days=2, seconds=3,
microseconds=456)])
+ frame = _RowPathFrame(pd)({"value": [Row(v=value) for value in values]},
dtype=object)
+ actual = _native_number_input_table(mock_connect,
frame).column(0).combine_chunks()
+ expected_type = pa.list_(pa.date32() if kind == "date" else
pa.duration("us"))
+ assert actual.type == expected_type
+ assert actual.to_pylist() == [[value] for value in values]
+
+
[email protected]("schema", [None, ["renamed"]])
[email protected]("large", [False, True])
[email protected]("infer_dict_as_map", [False, True])
+def test_customized_pandas_named_row_strings_keep_arrow_width_options(
+ mock_connect, schema, large, infer_dict_as_map
+):
+ import pyarrow as pa
+
+ pd = pytest.importorskip("pandas")
+ _, service = mock_connect
+ service.confs = {
+ "spark.sql.execution.arrow.useLargeVarTypes": str(large).lower(),
+ "spark.sql.execution.pandas.inferPandasDictAsMap":
str(infer_dict_as_map).lower(),
+ }
+ frame = _RowPathFrame(pd)({"value": [Row(a="x", b="longer"), None]},
dtype=object)
+ actual = _native_number_input_table(mock_connect, frame,
schema).column(0).combine_chunks()
+ # With no Spark coercion type, PyArrow infers ordinary string offsets. The
+ # schema=None dict option supplies a type and activates large variable
widths.
+ wide = large and infer_dict_as_map and schema is None
+ assert actual.type == pa.list_(pa.large_string() if wide else pa.string())
+ assert actual.to_pylist() == [["x", "longer"], None]
+
+
[email protected]("plain_column", [False, True])
+def
test_customized_pandas_multiple_named_row_columns_keep_names_padding(mock_connect,
plain_column):
+ pd = pytest.importorskip("pandas")
+ data = {"left": [Row(a=1, b=2), None], "right": [Row(x=3), Row(x=4)]}
+ expected = [{"first": [1, 2], "_2": [3]}, {"first": None, "_2": [4]}]
+ if plain_column:
+ data = {"left": data["left"], "text": ["a", "b"], "right":
data["right"]}
+ expected = [{"first": [1, 2], "_2": "a", "_3": [3]},
+ {"first": None, "_2": "b", "_3": [4]}]
+ frame = _RowPathFrame(pd)(data, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame, ["first"])
+ assert actual.to_pylist() == expected
+
+
[email protected]("row_position", [0, 3, 6])
+def
test_customized_pandas_named_rows_preserve_multiple_native_columns(mock_connect,
row_position):
+ from decimal import Decimal
+ import pyarrow as pa
+
+ pd = pytest.importorskip("pandas")
+ columns = [
+ ("number", [1, None, 3]),
+ ("text", ["first", "second", None]),
+ ("decimal", [Decimal("1.20"), None, Decimal("3.400")]),
+ ("mixed_decimal", [Decimal("1.20"), 2, None]),
+ ("nested", [[Decimal("1.2")], [Decimal("0.125")], None]),
+ ("flag", [True, False, None]),
+ ]
+ columns.insert(row_position, ("rows", [Row(a=1, b=2), None, Row(a=3,
b=4)]))
+ frame = _RowPathFrame(pd)(dict(columns), dtype=object)
+ actual = _native_number_input_table(mock_connect, frame)
+ assert actual.column_names == [name for name, _ in columns]
+ expected = [{name: values[i] for name, values in columns} for i in
range(3)]
+ for row, values in zip(expected, [[1, 2], None, [3, 4]]):
+ row["rows"] = values
+ assert actual.to_pylist() == expected
+ assert actual.column("decimal").type == pa.decimal128(4, 3)
+ assert actual.column("mixed_decimal").type == pa.decimal128(3, 2)
+ assert actual.column("nested").type == pa.list_(pa.decimal128(38, 3))
+
+
+def
test_customized_pandas_named_row_arrow_field_metadata_and_nullability_survive(
+ mock_connect, monkeypatch
+):
+ import pyarrow as pa
+ from pyspark.sql import _pandas_input
+
+ pd = pytest.importorskip("pandas")
+ original = _pandas_input.prepare_inferred_pandas_row_column
+
+ def tagged(*args):
+ data_type, table = original(*args)
+ field = table.schema.field(0)
+ field = pa.field(field.name, field.type, nullable=False,
metadata={b"source": b"row"})
+ return data_type, pa.Table.from_arrays(table.columns,
schema=pa.schema([field]))
+
+ monkeypatch.setattr(_pandas_input, "prepare_inferred_pandas_row_column",
tagged)
+ frame = _RowPathFrame(pd)({"value": [Row(a=1, b=2)]}, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame)
+ assert not actual.schema.field(0).nullable
+ assert actual.schema.field(0).metadata == {b"source": b"row"}
+ assert actual.to_pylist() == [{"value": [1, 2]}]
+
+
+def
test_customized_pandas_named_row_columns_align_different_arrow_chunks(mock_connect,
monkeypatch):
+ import pyarrow as pa
+ from pyspark.sql import _pandas_input
+
+ pd = pytest.importorskip("pandas")
+ original = _pandas_input.prepare_inferred_pandas_row_column
+
+ def chunked(values, name, *args):
+ data_type, table = original(values, name, *args)
+ split = 1 if name == "left" else 2
+ empty = table.slice(0, 0)
+ return data_type, pa.concat_tables([
+ empty, table.slice(0, split), empty, table.slice(split), empty,
+ ])
+
+ monkeypatch.setattr(_pandas_input, "prepare_inferred_pandas_row_column",
chunked)
+ frame = _RowPathFrame(pd)({
+ "left": [Row(v=1), Row(v=2), Row(v=3)],
+ "text": ["a", "b", "c"],
+ "right": [Row(v=4), Row(v=5), Row(v=6)],
+ }, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame)
+ assert actual.to_pylist() == [
+ {"left": [1], "text": "a", "right": [4]},
+ {"left": [2], "text": "b", "right": [5]},
+ {"left": [3], "text": "c", "right": [6]},
+ ]
+ assert actual.column(0).num_chunks == 3
+
+
+def
test_customized_pandas_named_rows_keep_native_fallback_without_pyarrow(mock_connect,
monkeypatch):
+ from pyspark.sql import _pandas_input
+
+ pd = pytest.importorskip("pandas")
+ monkeypatch.setattr(_pandas_input, "pyarrow_available", lambda: False)
+
+ def unexpected(*args):
+ raise AssertionError("unavailable PyArrow must retain native Row
conversion")
+
+ monkeypatch.setattr(_pandas_input, "inferred_pandas_row_columns",
unexpected)
+ frame = _RowPathFrame(pd)({"value": [Row(a=1, b="x")]}, dtype=object)
+ assert _native_number_input_table(mock_connect,
frame).column(0).to_pylist() == [
+ {"a": 1, "b": "x"}
+ ]
+
+
[email protected]("kind", ["overflow", "null_map_key", "decimal",
"encoder"])
[email protected]("row_first", [False, True])
+def test_customized_pandas_named_row_errors_follow_column_order(mock_connect,
kind, row_first):
+ from decimal import Decimal
+ from pyspark.errors import PySparkRuntimeError, PySparkTypeError,
PySparkValueError
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ native = {
+ "overflow": [2**63, 1],
+ "null_map_key": [{None: 1}, {"x": 2}],
+ "decimal": [Decimal("1.5"), 2.5],
+ "encoder": [[1], ["x"]],
+ }[kind]
+ columns = {"native": native, "rows": [Row(a=1, b="x"), Row(a=2, b="y")]}
+ if row_first:
+ columns = {"rows": columns["rows"], "native": native}
+ frame = _RowPathFrame(pd)(columns, dtype=object)
+ before = len(service.execute_requests)
+ if row_first:
+ error_type, message = PySparkValueError, r"with name 'rows'"
+ elif kind == "overflow":
+ error_type, message = OverflowError, "Python int too large"
+ elif kind in ("null_map_key", "decimal"):
+ error_type, message = PySparkTypeError, r"with name 'native'"
+ else:
+ # The inherited native encoder rejects the string in an inferred long
array.
+ error_type, message = PySparkRuntimeError, "Type mismatch in row data"
+ with pytest.raises(error_type, match=message) as error:
+ spark.createDataFrame(frame)
+ if not row_first and kind == "encoder":
+ assert "with name 'rows'" not in str(error.value)
+ assert len(service.execute_requests) == before
+
+
[email protected]("row_first", [False, True])
+def
test_customized_pandas_failed_named_rows_do_not_repeat_native_scalar_hooks(mock_connect,
row_first):
+ from pyspark.errors import PySparkValueError
+
+ pd = pytest.importorskip("pandas")
+ calls = []
+
+ class Indexed:
+ def __init__(self, value):
+ self.value = value
+
+ def __index__(self):
+ calls.append(self.value)
+ return self.value
+
+ columns = {"native": [Indexed(1), Indexed(2)],
+ "rows": [Row(a=1, b="x"), Row(a=2, b="y")]}
+ if row_first:
+ columns = {"rows": columns["rows"], "native": columns["native"]}
+ frame = _RowPathFrame(pd)(columns, dtype=object)
+ with pytest.raises(PySparkValueError, match=r"with name 'rows'"):
+ mock_connect[0].createDataFrame(frame)
+ # The fallback retains one native scalar traversal, including callbacks in
later
+ # columns on failing input; it does not retry objects to choose an earlier
error.
+ assert calls == [1, 2]
+
+
[email protected]("row_first", [False, True])
+def
test_customized_pandas_native_error_stops_later_hooks_in_its_column(mock_connect,
row_first):
+ from decimal import Decimal
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ calls = []
+ failure = LookupError("native column conversion failed")
+
+ class TracedDecimal(Decimal):
+ def as_tuple(self):
+ calls.append(str(self))
+ if self == Decimal("1.0"):
+ raise failure
+ return super().as_tuple()
+
+ columns = {"native": [TracedDecimal("1.0"), TracedDecimal("2.0")],
+ "rows": [Row(a=1), Row(a=2)]}
+ if row_first:
+ columns = {"rows": columns["rows"], "native": columns["native"]}
+ frame = _RowPathFrame(pd)(columns, dtype=object)
+ before = len(service.execute_requests)
+ with pytest.raises(LookupError, match="^native column conversion failed$")
as error:
+ spark.createDataFrame(frame)
+ assert error.value is failure
+ assert calls == ["1.0"]
+ assert len(service.execute_requests) == before
+
+
[email protected]("error_type", [KeyboardInterrupt, SystemExit,
GeneratorExit])
+def
test_customized_pandas_native_base_exception_stops_later_hooks(mock_connect,
error_type):
+ from decimal import Decimal
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ calls = []
+ failure = error_type("native column interrupted")
+
+ class InterruptedDecimal(Decimal):
+ def as_tuple(self):
+ calls.append("native")
+ raise failure
+
+ class LaterIndexed:
+ def __index__(self):
+ calls.append("later")
+ return 1
+
+ frame = _RowPathFrame(pd)({
+ "rows": [Row(a=1), Row(a=2)],
+ "native": [InterruptedDecimal("1.0"), InterruptedDecimal("2.0")],
+ "later": [LaterIndexed(), LaterIndexed()],
+ }, dtype=object)
+ before = len(service.execute_requests)
+ with pytest.raises(error_type, match="^native column interrupted$") as
error:
+ spark.createDataFrame(frame)
+ assert error.value is failure
+ assert calls == ["native"]
+ assert len(service.execute_requests) == before
+
+
[email protected]("native_invalid", [False, True])
[email protected]("failure_kind", ["lookup", "discovery"])
+def test_customized_pandas_helper_reported_row_error_follows_column_order(
+ mock_connect, monkeypatch, native_invalid, failure_kind
+):
+ from pyspark.sql import _pandas_input
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ # Inject the discovery error without constructing a cyclic or deep input.
+ failure = (ValueError("cyclic container in inferred pandas Row discovery")
+ if failure_kind == "discovery" else LookupError("Row values
unavailable"))
+ calls = []
+
+ def reported_error(rows, width, candidates):
+ calls.append((len(rows), width, list(candidates)))
+ return [(1, failure)]
+
+ def unexpected(*args):
+ raise AssertionError("a helper-reported exception must not be encoded
as a Row column")
+
+ monkeypatch.setattr(_pandas_input, "inferred_pandas_row_columns",
reported_error)
+ monkeypatch.setattr(_pandas_input, "prepare_inferred_pandas_row_column",
unexpected)
+ frame = _RowPathFrame(pd)({
+ "native": [2**63 if native_invalid else 1], "rows": [Row(a=2)],
+ }, dtype=object)
+ before = len(service.execute_requests)
+ expected = OverflowError if native_invalid else type(failure)
+ message = ("^Python int too large to convert to C long$" if native_invalid
+ else "^" + str(failure) + "$")
+ with pytest.raises(expected, match=message) as error:
+ spark.createDataFrame(frame)
+ if not native_invalid:
+ assert error.value is failure
+ assert calls == [(1, 2, [0, 1])]
+ assert len(service.execute_requests) == before
+
+
+def
test_customized_pandas_row_discovery_walks_only_object_columns(mock_connect,
monkeypatch):
+ from pyspark.sql import _pandas_input
+
+ pd = pytest.importorskip("pandas")
+ spark, _ = mock_connect
+ walk = _pandas_input.inferred_pandas_row_columns
+ calls = []
+
+ def recorded(rows, width, candidates):
+ calls.append(list(candidates))
+ return walk(rows, width, candidates)
+
+ monkeypatch.setattr(_pandas_input, "inferred_pandas_row_columns", recorded)
+ # Only a column of Python objects can hold a Row, so the cells of numeric,
boolean,
+ # string and datetime columns are not walked, and a frame of them not at
all.
+ frame = _RowPathFrame(pd)({
+ "n": [1, 2], "f": [0.5, None], "rows": [Row(a=1, b=2), Row(a=3, b=4)],
+ "b": [True, False], "t": pd.to_datetime(["2024-01-01", None]),
+ })
+ spark.createDataFrame(frame)
+ assert calls == [[2]]
+ spark.createDataFrame(_RowPathFrame(pd)({"n": [1, 2], "f": [0.5, None]}))
+ assert calls == [[2]]
+
+
[email protected]("native_invalid", [False, True])
+def test_customized_pandas_row_setup_conf_error_follows_column_order(
+ mock_connect, monkeypatch, native_invalid
+):
+ from pyspark.errors.exceptions.connect import SparkConnectGrpcException,
StatusCode
+
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ missing = "spark.sql.session.localRelationCacheThreshold"
+ # An instance override leaves the shared server's defaults intact after
this test.
+ monkeypatch.setattr(service, "default_confs", {
+ key: value for key, value in service.default_confs.items() if key !=
missing
+ })
+ frame = _RowPathFrame(pd)({
+ "native": [2**63 if native_invalid else 1], "rows": [Row(a=2)],
+ }, dtype=object)
+ before = len(service.execute_requests)
+ if native_invalid:
+ with pytest.raises(OverflowError, match="^Python int too large to
convert to C long$"):
+ spark.createDataFrame(frame)
+ else:
+ with pytest.raises(SparkConnectGrpcException,
match=r"\[SQL_CONF_NOT_FOUND\]") as error:
+ spark.createDataFrame(frame)
+ assert error.value.getGrpcStatusCode() == StatusCode.INTERNAL
+ assert missing in service.read_confs
+ assert len(service.execute_requests) == before
+
+
[email protected]("schema", [None, ["renamed"]])
+def test_customized_pandas_without_rows_skips_arrow_settings(mock_connect,
schema):
+ pd = pytest.importorskip("pandas")
+ spark, service = mock_connect
+ arrow_settings = {
+ "spark.sql.timestampType",
+ "spark.sql.session.timeZone",
+ "spark.sql.execution.arrow.useLargeVarTypes",
+ "spark.sql.session.localRelationCacheThreshold",
+ "spark.sql.session.localRelationSizeLimit",
+ "spark.sql.session.localRelationChunkSizeRows",
+ "spark.sql.session.localRelationChunkSizeBytes",
+ "spark.sql.session.localRelationBatchOfChunksSizeBytes",
+ "spark.sql.execution.pandas.convertToArrowArraySafely",
+ "spark.sql.execution.pandas.inferPandasDictAsMap",
+ }
+ frame = _RowPathFrame(pd)({"native": [1, 2], "text": ["a", "b"]},
dtype=object)
+ before_confs = len(service.read_confs)
+ before_execute = len(service.execute_requests)
+ assert type(spark.createDataFrame(frame, schema)).__name__ == "DataFrame"
+ assert arrow_settings.isdisjoint(service.read_confs[before_confs:])
+ assert len(service.execute_requests) == before_execute
+
+
+def
test_customized_pandas_named_rows_from_widened_normalization_keep_schema_names(mock_connect):
+ pd = pytest.importorskip("pandas")
+
+ class Frame(pd.DataFrame):
+ def astype(self, *args, **kwargs):
+ return self
+
+ def where(self, *args, **kwargs):
+ return pd.DataFrame({"first": [1], "second": [Row(a=2, b=3)]},
dtype=object)
+
+ frame = Frame({"original": [1]}, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame, ["x", "y"])
+ assert actual.to_pylist() == [{"x": 1, "y": [2, 3]}]
+
+
+def
test_customized_pandas_named_row_inference_preserves_frame_and_other_column_hooks(mock_connect):
+ from decimal import Decimal
+
+ pd = pytest.importorskip("pandas")
+ calls = []
+
+ class Frame(pd.DataFrame):
+ @property
+ def _constructor(self):
+ return Frame
+
+ def notna(self):
+ calls.append("notna")
+ return super().notna()
+
+ def astype(self, *args, **kwargs):
+ calls.append("astype")
+ return super().astype(*args, **kwargs)
+
+ def where(self, *args, **kwargs):
+ calls.append("where")
+ return super().where(*args, **kwargs)
+
+ class IndexedString(str):
+ def __index__(self):
+ calls.append("index")
+ return 42
+
+ class TracedDecimal(Decimal):
+ def __str__(self):
+ calls.append("decimal str")
+ return super().__str__()
+
+ def as_tuple(self):
+ calls.append("decimal tuple")
+ return super().as_tuple()
+
+ frame = Frame({"row": [Row(a=1, b=2)], "text": [IndexedString("x")],
+ "decimal": [TracedDecimal("1.20")]}, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame)
+ assert actual.to_pylist() == [{"row": [1, 2], "text": 42, "decimal":
Decimal("1.20")}]
+ assert calls[:3] == ["notna", "astype", "where"]
+ assert calls[3:] == ["index", "decimal str", "decimal tuple", "decimal
tuple"]
+
+
+def
test_pandas_named_row_adaptation_accepts_tuple_rows_without_reading_fields():
+ # Exercise the shipped Row representation and its subclasses: field
metadata
+ # and iterator overrides must not change the positional values Arrow sees.
+ from pyspark.sql import _pandas_input
+
+ class TupleRow(Row):
+ def __iter__(self):
+ raise AssertionError("inferred pandas conversion used a Row
iterator override")
+
+ @property
+ def __fields__(self):
+ raise AssertionError("inferred pandas conversion read Row field
names")
+
+ value = TupleRow(1, TupleRow(2, 3))
+ assert _pandas_input.inferred_pandas_row_columns([[value]], 1) == [(0,
[(1, (2, 3))])]
+ key = TupleRow(1, 2)
+ assert _pandas_input.inferred_pandas_row_columns([[{key: 3}]], 1) == [
+ (0, [{(1, 2): 3}])
+ ]
+ adapted = _pandas_input.inferred_pandas_row_columns([[{key: 3}]], 1)
+ assert next(iter(adapted[0][1][0])) is key
+
+
+def test_pandas_named_row_discovery_retains_key_hash_error_column():
+ from pyspark.sql import _pandas_input
+
+ cause = ValueError("key callback unavailable")
+ failure = LookupError("dict replacement unavailable")
+ failure.__cause__ = cause
+ fail_hash = False
+ calls = []
+
+ class Key:
+ def __hash__(self):
+ calls.append("hash")
+ if fail_hash:
+ raise failure
+ return 17
+
+ key = Key()
+ original_row = Row(a=1, b=2)
+ original = {key: original_row}
+ calls.clear()
+ fail_hash = True
+ rows = [[1, original], [2, original]]
+ errors = _pandas_input.inferred_pandas_row_columns(rows, 2)
+ assert len(errors) == 1
+ assert errors[0][0] == 1
+ assert errors[0][1] is failure
+ assert errors[0][1].__cause__ is cause
+ assert str(errors[0][1]) == "dict replacement unavailable"
+ assert calls == ["hash"]
+ assert len(original) == 1
+ assert next(iter(original)) is key
+ assert list(original.values())[0] is original_row
+ assert rows[0][1] is original and rows[1][1] is original
+
+
[email protected]("first", [None, False, 1, 1.5, 2 + 3j, "x", b"x",
bytearray(b"x")])
+def
test_pandas_named_row_detection_keeps_later_nested_rows_after_scalars(first):
+ from pyspark.sql import _pandas_input
+
+ nested = {"child": [0, (Row(a=1, b=2),)]}
+ adapted = _pandas_input.inferred_pandas_row_columns([[first, first],
[nested, first]], 2)
+ assert len(adapted) == 1
+ assert adapted[0][0] == 0
+ assert adapted[0][1][0] is first
+ assert adapted[0][1][1] == {"child": [0, ((1, 2),)]}
+
+
+def test_pandas_named_row_detection_does_not_compare_or_hash_cell_types():
+ from pyspark.sql import _pandas_input
+
+ class Meta(type):
+ def __eq__(cls, other):
+ raise AssertionError("Row detection compared a cell type")
+
+ def __hash__(cls):
+ raise AssertionError("Row detection hashed a cell type")
+
+ class Opaque(metaclass=Meta):
+ pass
+
+ value = Opaque()
+ adapted = _pandas_input.inferred_pandas_row_columns([[value], [Row(a=1)]],
1)
+ assert adapted[0][0] == 0
+ assert adapted[0][1][0] is value
+ assert adapted[0][1][1] == (1,)
+
+
+def test_pandas_named_row_adaptation_revisits_shared_acyclic_containers():
+ from pyspark.sql import _pandas_input
+
+ original_row = Row(a=1, b=2)
+ shared = [original_row]
+ untouched = {"numbers": [3, 4]}
+ value = {"left": shared, "right": (shared,), "untouched": untouched}
+ adapted = _pandas_input.inferred_pandas_row_columns([[value], [value]], 1)
+ assert len(adapted) == 1
+ assert adapted[0][0] == 0
+ values = adapted[0][1]
+ expected = {"left": [(1, 2)], "right": ([(1, 2)],), "untouched": untouched}
+ assert values == [expected, expected]
+ assert values[0] is not values[1]
+ for converted in values:
+ assert converted["left"] is not converted["right"][0]
+ assert converted["untouched"] is untouched
+ assert value["left"] is shared
+ assert value["right"][0] is shared
+ assert shared[0] is original_row
+
+
[email protected]("parent_kind", ["list", "tuple", "dict"])
+def
test_pandas_named_row_discovery_active_id_guard_retains_column(monkeypatch,
parent_kind):
+ from pyspark.sql import _pandas_input
+
+ child = Row(a=1, b=2)
+ if parent_kind == "list":
+ parent = [child]
+ elif parent_kind == "tuple":
+ parent = (child,)
+ else:
+ parent = {"child": child}
+ original_id = id
+ parent_id = original_id(parent)
+ guard_calls = []
+
+ def controlled_id(value):
+ if value is parent:
+ guard_calls.append("parent")
+ if value is child:
+ guard_calls.append("child")
+ return parent_id
+ return original_id(value)
+
+ # This ordinary acyclic input exercises the guard through a simulated ID
collision.
+ monkeypatch.setattr(_pandas_input, "id", controlled_id, raising=False)
+ errors = _pandas_input.inferred_pandas_row_columns([[1, parent], [2,
None]], 2)
+ assert len(errors) == 1
+ assert errors[0][0] == 1
+ assert type(errors[0][1]) is ValueError
+ assert str(errors[0][1]) == "cyclic container in inferred pandas Row
discovery"
+ assert guard_calls == ["parent", "child"]
+ assert (parent["child"] if parent_kind == "dict" else parent[0]) is child
+ assert tuple.__getitem__(child, slice(None)) == (1, 2)
+ assert child.__fields__ == ["a", "b"]
+
+
+def test_pandas_named_row_discovery_reports_stable_key_hash_hook():
+ from pyspark.sql import _pandas_input
+
+ calls = []
+
+ class StableKey:
+ def __hash__(self):
+ calls.append("hash")
+ return 17
+
+ key = StableKey()
+ original_row = Row(a=1, b=2)
+ original = {key: original_row}
+ calls.clear()
+ adapted = _pandas_input.inferred_pandas_row_columns([[original]], 1)
+ converted = adapted[0][1][0]
+ assert len(converted) == 1
+ assert next(iter(converted)) is key
+ assert list(converted.values()) == [(1, 2)]
+ assert list(original.values())[0] is original_row
+ # This single stable, collision-free key needs one replacement hash lookup.
+ assert calls == ["hash"]
+
+
+def
test_named_row_struct_schemas_and_plain_pandas_arrow_are_preserved(mock_connect,
monkeypatch):
+ from pyspark.sql import _pandas_input
+
+ pd = pytest.importorskip("pandas")
+ struct = T.StructType().add("a", T.LongType()).add("b", T.StringType())
+ schema = T.StructType().add("value", struct)
+ # An explicit struct and local-row inference retain named structures.
+ frame = _RowPathFrame(pd)({"value": [Row(a=1, b="x")]}, dtype=object)
+
+ def unexpected(*args):
+ raise AssertionError("input unexpectedly used inferred Row adaptation")
+
+ monkeypatch.setattr(_pandas_input, "inferred_pandas_row_columns",
unexpected)
+ assert _native_number_input_table(mock_connect, frame,
schema).column(0).to_pylist() == [
+ {"a": 1, "b": "x"}
+ ]
+ assert _native_number_input_table(mock_connect, [(Row(a=1,
b="x"),)]).column(0).to_pylist() == [
+ {"a": 1, "b": "x"}
+ ]
+ # Ordinary pandas continues to use its existing whole-frame Arrow route.
+ plain = pd.DataFrame({"value": [(1, 2), (3, 4)]}, dtype=object)
+ assert _native_number_input_table(mock_connect,
plain).column(0).to_pylist() == [[1, 2], [3, 4]]
+
+
@pytest.mark.parametrize("value", [
None, False, True, 0, -1, -(2**63), 2**63 - 1,
0.0, -0.0, 1.25, float("inf"), float("-inf"),
@@ -8186,7 +9007,12 @@ def
test_pandas_input_number_subclasses_decimal_and_conversion_protocols(mock_co
def test_local_input_native_numbers_inside_nested_values(mock_connect):
value = Row(items=[1, 2, None], mapping={"x": 2**63 - 1})
- actual = _native_number_input_table(mock_connect, [Row(value=value)],
source="pandas").column(0)[0].as_py()
+ schema = T.StructType().add("value", T.StructType()
+ .add("items", T.ArrayType(T.LongType()))
+ .add("mapping", T.MapType(T.StringType(),
T.LongType())))
+ actual = _native_number_input_table(
+ mock_connect, [Row(value=value)], schema, source="pandas"
+ ).column(0)[0].as_py()
assert actual["items"] == [1, 2, None]
assert dict(actual["mapping"]) == {"x": 2**63 - 1}
@@ -8197,9 +9023,15 @@ def
test_local_input_native_numbers_inside_nested_values(mock_connect):
(lambda: Row("a", "b")(1, "x"), {"a": 1, "b": "x"}),
(lambda: Row("a", "b")(1), {"a": 1}),
])
-def test_tuple_rows_remain_named_structs_in_native_input(mock_connect, source,
make, expected):
- # A customized pandas subclass retains the native row path. Plain pandas
- # frames take the separate Arrow path checked below.
+def test_tuple_rows_remain_named_structs_in_native_input(
+ mock_connect, monkeypatch, source, make, expected
+):
+ # Keep the pandas cases on the native fallback contract; inferred Row
columns
+ # with PyArrow available are covered by the adaptation tests above.
+ if source == "pandas":
+ from pyspark.sql import _pandas_input
+
+ monkeypatch.setattr(_pandas_input, "pyarrow_available", lambda: False)
value = make()
actual = _native_number_input_table(
mock_connect, [(value,)], source=source
@@ -8283,6 +9115,25 @@ def
test_pandas_tuple_field_lookup_propagates_errors(mock_connect):
)
[email protected]("layout", ["arrays", "maps"])
+def
test_pandas_native_inferred_numbers_inside_nested_dict_values(mock_connect,
layout):
+ import pyarrow as pa
+
+ # Row-free dict cells retain native inference, whose dicts become Arrow
maps.
+ if layout == "arrays":
+ value = {"items": [1, 2, None], "limits": [-(2**63), 2**63 - 1]}
+ expected_type = pa.map_(pa.string(), pa.list_(pa.int64()))
+ else:
+ value = {"left": {"low": -(2**63), "high": 2**63 - 1}, "right":
{"mid": 0}}
+ expected_type = pa.map_(pa.string(), pa.map_(pa.string(), pa.int64()))
+ actual = _native_number_input_table(
+ mock_connect, [(value,)], source="pandas"
+ ).column(0).combine_chunks()
+ expected = pa.array([value], type=expected_type)
+ assert actual.type == expected_type
+ assert actual.equals(expected)
+
+
# Exact list/tuple conversion and pandas input IPC regressions.
from datetime import date as container_input_date, datetime as
container_input_datetime
from decimal import Decimal as ContainerInputDecimal
@@ -8474,7 +9325,7 @@ from decimal import Decimal as _exact_date_Decimal
from pyspark.sql import Row as _exact_date_Row
-def _exact_date_converted_value(mock_connect, value):
+def _exact_date_converted_value(mock_connect, value, schema=None):
import pyarrow as pa
pd = pytest.importorskip("pandas")
@@ -8484,7 +9335,7 @@ def _exact_date_converted_value(mock_connect, value):
# infer.convert, which intentionally has different subclass/type semantics.
data = _RowPathFrame(pd)({"value": [value]}, dtype=object)
before = len(service.execute_requests)
- spark.createDataFrame(data).toArrow()
+ spark.createDataFrame(data, schema).toArrow()
requests = service.execute_requests
assert len(requests) == before + 1
request = parse_message(requests[-1])
@@ -8570,7 +9421,14 @@ def
test_exact_date_nested_unrelated_values(mock_connect):
mapping={"epoch": _exact_date_date(1970, 1, 1)},
nested=_exact_date_Row(day=_exact_date_date(2000, 2, 29)),
amount=_exact_date_Decimal("-12.340"), number=42, flag=True,
label="date")
- actual = _exact_date_converted_value(mock_connect, value)
+ schema = T.StructType().add("value", T.StructType()
+ .add("items", T.ArrayType(T.DateType()))
+ .add("mapping", T.MapType(T.StringType(),
T.DateType()))
+ .add("nested", T.StructType().add("day",
T.DateType()))
+ .add("amount", T.DecimalType(38, 3))
+ .add("number", T.LongType()).add("flag",
T.BooleanType())
+ .add("label", T.StringType()))
+ actual = _exact_date_converted_value(mock_connect, value, schema)
assert actual["items"] == [_exact_date_date.min, None,
_exact_date_date.max]
assert dict(actual["mapping"]) == {"epoch": _exact_date_date(1970, 1, 1)}
assert actual["nested"]["day"] == _exact_date_date(2000, 2, 29)
@@ -8578,6 +9436,33 @@ def
test_exact_date_nested_unrelated_values(mock_connect):
assert (actual["number"], actual["flag"], actual["label"]) == (42, True,
"date")
+def
test_exact_date_native_inferred_nested_dict_and_unrelated_values(mock_connect):
+ import pyarrow as pa
+
+ pd = pytest.importorskip("pandas")
+ values = {
+ "days": [{"limits": [_exact_date_date.min, None, _exact_date_date.max],
+ "epoch": [_exact_date_date(1970, 1, 1)]}],
+ "nested": [{"outer": {"day": _exact_date_date(2000, 2, 29)}}],
+ "amounts": [[_exact_date_Decimal("-12.340")]],
+ "number": [42], "flag": [True], "label": ["date"],
+ }
+ frame = _RowPathFrame(pd)(values, dtype=object)
+ actual = _native_number_input_table(mock_connect, frame)
+ expected_types = {
+ "days": pa.map_(pa.string(), pa.list_(pa.date32())),
+ "nested": pa.map_(pa.string(), pa.map_(pa.string(), pa.date32())),
+ "amounts": pa.list_(pa.decimal128(38, 3)),
+ "number": pa.int64(), "flag": pa.bool_(), "label": pa.string(),
+ }
+ expected = pa.table({
+ name: pa.array(column, type=expected_types[name]) for name, column in
values.items()
+ })
+ actual.validate(full=True)
+ assert actual.schema == expected.schema
+ assert actual.equals(expected)
+
+
def test_exact_date_named_impostor_rejected(mock_connect):
pd = pytest.importorskip("pandas")
from pyspark.errors import PySparkValueError
@@ -9567,16 +10452,15 @@ def
test_decimal_quanta_restore_outer_conversion_after_reentry(decimal_ipc_sessi
@pytest.mark.parametrize("schema_kind", ["inferred", "names"])
@pytest.mark.parametrize("layout", [
- "array", "nested_array", "struct", "mixed_struct", "array_struct",
"map_values", "map_keys",
+ "array", "nested_array", "row", "array_row", "map_values", "map_keys",
])
def test_pandas_nested_decimals_use_every_observed_scale(mock_connect, layout,
schema_kind):
from decimal import Decimal
import pyarrow as pa
decimals = [Decimal("1.5"), Decimal("1.25"), Decimal("0.003"),
Decimal("1E+3")]
- # Nested inferred precision remains 38 (SPARK-60696; see
dev/parity/known-differences.md).
- # Widen only the scale to preserve all values without changing the
inherited container
- # or non-Decimal type inference.
+ # Non-Row containers retain the native precision of 38 (SPARK-60696). A
column
+ # containing Rows follows Arrow's array inference, including Decimal
precision.
decimal_type = pa.decimal128(38, 3)
if layout == "array":
values = [[decimals[0], decimals[1]], None, [], decimals[2:]]
@@ -9586,13 +10470,11 @@ def
test_pandas_nested_decimals_use_every_observed_scale(mock_connect, layout, s
values = [[[decimals[0]], []], None, [[decimals[1]], decimals[2:]]]
expected_values = values
expected_type = pa.list_(pa.list_(decimal_type))
- elif layout in ("struct", "mixed_struct", "array_struct"):
+ elif layout in ("row", "array_row"):
values = [Row(d=value, keep=index) for index, value in
enumerate(decimals)]
- expected_values = [{"d": value, "keep": index} for index, value in
enumerate(decimals)]
- expected_type = pa.struct([pa.field("d", decimal_type),
pa.field("keep", pa.int64())])
- if layout == "mixed_struct":
- values = [values[0], *expected_values[1:]]
- if layout == "array_struct":
+ expected_values = [[value, Decimal(index)] for index, value in
enumerate(decimals)]
+ expected_type = pa.list_(pa.decimal128(7, 3))
+ if layout == "array_row":
values = [[values[0]], None, values[1:]]
expected_values = [[expected_values[0]], None, expected_values[1:]]
expected_type = pa.list_(expected_type)
@@ -9619,6 +10501,27 @@ def
test_pandas_nested_decimals_use_every_observed_scale(mock_connect, layout, s
assert actual.equals(expected)
[email protected]("schema_kind", ["inferred", "names"])
+def
test_pandas_nested_decimals_mixed_row_dict_raise_arrow_errors(mock_connect,
schema_kind):
+ from decimal import Decimal
+ from pyspark.errors import PySparkValueError
+
+ _, service = mock_connect
+ values = [
+ Row(d=Decimal("1.5"), keep=0),
+ {"d": Decimal("1.25"), "keep": 1},
+ {"d": Decimal("0.003"), "keep": 2},
+ {"d": Decimal("1E+3"), "keep": 3},
+ ]
+ names = ["renamed"] if schema_kind == "names" else None
+ before_execute = len(service.execute_requests)
+ with pytest.raises(PySparkValueError, match=r"pandas.Series \(object\)"):
+ _native_number_input_table(
+ mock_connect, [(value,) for value in values], names,
source="pandas"
+ )
+ assert len(service.execute_requests) == before_execute
+
+
@pytest.mark.parametrize("scale", [38, 39, 50, 128, 5_000_000_000])
def test_pandas_nested_decimal_scale_bounds(mock_connect, scale):
from decimal import Decimal
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]