gengliangwang commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4580588330
########## sql/native/rust/src/stream.rs: ########## @@ -0,0 +1,1014 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +use std::ffi::{c_char, c_int, c_void, CString}; +use std::sync::Arc; + +use arrow_array::ffi::FFI_ArrowArray; +use arrow_array::ffi_stream::FFI_ArrowArrayStream; +use arrow_array::types::{Decimal128Type, DecimalType}; +use arrow_array::{Array, RecordBatch, StructArray}; +use arrow_data::ArrayData; +use arrow_schema::{ffi::FFI_ArrowSchema, DataType, Field, Fields, Schema, SchemaRef, TimeUnit}; + +use super::{c_message, drop_provider, provider_call}; +use crate::{PartitionReader, Result}; + +struct StreamState<'task> { + reader: Option<PartitionReader<'task>>, + // The schema to read, whose columns, Spark types, and nullability each batch must have. + expected: SchemaRef, + // The schema of the stream: that of the first batch, which every batch must have, or + // the schema to read of a reader without batches. Unknown until either is read. + schema: Option<SchemaRef>, + // The schema of the last batch that the reader returned, with the indices of the columns + // to read in it, or None when it has exactly those columns. + projection: Option<(SchemaRef, Option<Vec<usize>>)>, + // The first batch, when get_schema read it to learn the schema. + pending: Option<ArrayData>, + last_error: Option<CString>, + finished: bool, +} + +impl StreamState<'_> { + /// Reads and checks the next batch. The first batch, or the end of the reader, + /// determines the schema of the stream. + fn read_next(&mut self) -> Result<Option<ArrayData>> { + let Some(batch) = self.reader.as_mut().expect("reader is present").next() else { + self.finished = true; + self.schema.get_or_insert_with(|| self.expected.clone()); + return Ok(None); + }; + let batch = self.project(batch?)?; + match &self.schema { + Some(schema) if batch.schema() != *schema => { + return Err(schema_change(schema, &batch.schema()).into()); + } + Some(_) => {} + None => { + if canonical_fields(batch.schema().fields())? + != canonical_fields(self.expected.fields())? + { + return Err("executor reader schema does not match the schema to read".into()); + } + self.schema = Some(batch.schema()); + } + } + let data = StructArray::from(batch).to_data(); + validate_layout(&data)?; + for (column, field) in data.child_data().iter().zip(self.expected.fields()) { + check_values(column, field, field.name(), None)?; + } + Ok(Some(data)) + } + + /// Keeps the columns of the schema to read, in its order, from a batch that may have more, + /// such as all the columns of the source. Resolves the columns once for each schema. + fn project(&mut self, batch: RecordBatch) -> Result<RecordBatch> { + let schema = batch.schema(); + if !matches!(&self.projection, Some((last, _)) if *last == schema) { + self.projection = Some((schema.clone(), projection(&schema, &self.expected)?)); + } + match &self.projection { + Some((_, Some(indices))) => Ok(batch.project(indices)?), + _ => Ok(batch), + } + } +} + +/// Describes how the schema of a batch differs from that of the stream. Both have the +/// columns of the schema to read, so either a column or the metadata of the schema differs. +fn schema_change(stream: &Schema, batch: &Schema) -> String { + let mut fields = stream.fields().iter().zip(batch.fields()); + match fields.find(|(first, field)| first != field) { + Some((first, field)) => format!( + "reader returned a batch with a different schema: the column {} is {first:?} in \ + the first batch and {field:?} in this one", + first.name() + ), + None => "reader returned a batch with a different schema: its metadata differs".to_owned(), + } +} + +/// The indices of the columns of the schema to read, in its order, in the schema of a batch +/// that may have more, or None when the batch has exactly those columns. +fn projection(schema: &Schema, expected: &Schema) -> Result<Option<Vec<usize>>> { + let names = |fields: &Fields| fields.iter().map(|field| field.name().clone()).collect(); + let actual: Vec<String> = names(schema.fields()); + let wanted: Vec<String> = names(expected.fields()); + if actual == wanted { + return Ok(None); + } + let indices = + wanted + .iter() + .map(|name| { + actual.iter().position(|actual| actual == name).ok_or_else(|| { + format!("reader returned a batch without the column {name} of the schema to read") + }) + }) + .collect::<std::result::Result<Vec<_>, _>>()?; + Ok(Some(indices)) +} + +impl Drop for StreamState<'_> { + fn drop(&mut self) { + // release has no error return channel, but it must never unwind into C. + if let Some(reader) = self.reader.take() { + drop_provider(reader); + } + } +} + +/// The reader may borrow the host task context until the consumer releases +/// this stream. Erasure into C private_data is confined to this boundary. +/// +/// # Safety +/// The caller must keep everything borrowed by the reader alive until release, +/// and the consumer must obey the Arrow C Stream ownership protocol. +pub(super) unsafe fn export( + reader: PartitionReader<'_>, + expected_schema: &SchemaRef, +) -> FFI_ArrowArrayStream { + let state = Box::new(StreamState { + reader: Some(reader), + expected: expected_schema.clone(), + schema: None, + projection: None, + pending: None, + last_error: None, + finished: false, + }); + FFI_ArrowArrayStream { + get_schema: Some(get_schema), + get_next: Some(get_next), + get_last_error: Some(get_last_error), + release: Some(release), + private_data: Box::into_raw(state).cast::<c_void>(), + } +} + +fn callback( + state: &mut StreamState<'_>, + action: impl FnOnce(&mut StreamState<'_>) -> Result<()>, +) -> c_int { + // A failed stream stays failed, with its error: an engine that calls it again must not + // read a failed partition as complete. + if state.last_error.is_some() { + return 5; + } + let Err(message) = provider_call(|| action(state)) else { + return 0; + }; + state.last_error = Some(c_message(message)); + 5 // EIO; get_last_error supplies the provider's actual error message. +} + +unsafe extern "C" fn get_schema( + stream: *mut FFI_ArrowArrayStream, + output: *mut FFI_ArrowSchema, +) -> c_int { + let state = unsafe { &mut *(*stream).private_data.cast::<StreamState<'_>>() }; + callback(state, |state| { + // The reader does not declare a schema: read the first batch, which has it. + if state.schema.is_none() && !state.finished { + state.pending = state.read_next()?; + } + let schema = state.schema.as_ref().unwrap_or(&state.expected); + let schema = FFI_ArrowSchema::try_from(schema.as_ref())?; + unsafe { output.write(schema) }; + Ok(()) + }) +} + +unsafe extern "C" fn get_next( + stream: *mut FFI_ArrowArrayStream, + output: *mut FFI_ArrowArray, +) -> c_int { + let state = unsafe { &mut *(*stream).private_data.cast::<StreamState<'_>>() }; + callback(state, |state| { + let data = match state.pending.take() { + Some(data) => Some(data), + None if state.finished => None, + None => state.read_next()?, + }; + match data { + Some(data) => unsafe { output.write(FFI_ArrowArray::new(&data)) }, + // A null release callback denotes EOF, including for zero-column data. + None => unsafe { output.write(FFI_ArrowArray::empty()) }, + } + Ok(()) + }) +} + +unsafe extern "C" fn get_last_error(stream: *mut FFI_ArrowArrayStream) -> *const c_char { + let state = unsafe { &*(*stream).private_data.cast::<StreamState<'_>>() }; + state + .last_error + .as_ref() + .map_or(std::ptr::null(), |error| error.as_ptr()) +} + +unsafe extern "C" fn release(stream: *mut FFI_ArrowArrayStream) { + let state = unsafe { (*stream).private_data.cast::<StreamState<'_>>() }; + // Mark released before destruction. The consumer owns the stream structure. + unsafe { stream.write(FFI_ArrowArrayStream::empty()) }; + drop_provider(unsafe { Box::from_raw(state) }); +} + +// Compare the Spark logical types of version 1 of the ABI, ignoring Arrow +// nullability/metadata and the interchangeable physical encodings of strings and +// binary data. Spark also distinguishes only the presence of a time zone, not its +// spelling. Nullability is checked against the data instead, in check_values. +pub(crate) fn validate_schema(schema: &SchemaRef) -> Result<()> { + canonical_fields(schema.fields())?; + Ok(()) +} + +pub(crate) fn canonical_fields(fields: &Fields) -> Result<Fields> { + fields + .iter() + .map(|field| { + Ok(Arc::new(Field::new( + field.name(), + canonical_type(field.data_type())?, + false, + ))) + }) + .collect() +} + +fn canonical_type(data_type: &DataType) -> Result<DataType> { + use DataType::*; + Ok(match data_type { + Boolean | Int8 | Int16 | Int32 | Int64 | Float32 | Float64 | Date32 => data_type.clone(), + Utf8 | LargeUtf8 | Utf8View => Utf8, + Binary | LargeBinary | BinaryView => Binary, + Decimal128(precision, _) if *precision > 0 && *precision <= 38 => data_type.clone(), + Timestamp(TimeUnit::Microsecond, tz) => { + Timestamp(TimeUnit::Microsecond, tz.as_ref().map(|_| "UTC".into())) + } + Struct(fields) => Struct(canonical_fields(fields)?), + List(field) => List(Arc::new(Field::new( + "item", + canonical_type(field.data_type())?, + false, + ))), + Map(entries, _) => { + let Struct(fields) = entries.data_type() else { + return Err("Arrow map entries must be a struct".into()); + }; + if fields.len() != 2 { + return Err("Arrow map entries must have a key and a value".into()); + } + let entries = Struct( + vec![ + Field::new("key", canonical_type(fields[0].data_type())?, false), + Field::new("value", canonical_type(fields[1].data_type())?, false), + ] + .into(), + ); + Map(Arc::new(Field::new("entries", entries, false)), false) + } + _ => return Err(format!("unsupported Spark Arrow type: {data_type}").into()), + }) +} + +/// Rejects a null where the schema to read declares a column, a field, an element, or a map +/// value not nullable, unless its parent is null, as Spark does after reading, and a decimal +/// value that does not fit in the precision of its type, as Spark does when it converts the +/// value to a row. `referenced` tells which values belong to a parent value that is not null. +fn check_values( + data: &ArrayData, + field: &Field, + column: &str, + referenced: Option<&[bool]>, +) -> Result<()> { + let is_referenced = |index: usize| referenced.is_none_or(|mask| mask[index]); + if !field.is_nullable() + && data.null_count() > 0 + && (0..data.len()).any(|index| data.is_null(index) && is_referenced(index)) + { + return Err(format!( + "The column {column} has a null, but the schema to read declares it not nullable" + ) + .into()); + } + if !needs_check(field.data_type()) { + return Ok(()); + } + let valid = |index: usize| data.is_valid(index) && is_referenced(index); + match field.data_type() { + DataType::Decimal128(precision, scale) => { + let values = data.buffer::<i128>(0); + for index in (0..data.len()).filter(|index| valid(*index)) { + let value = values[index]; + if Decimal128Type::validate_decimal_precision(value, *precision, *scale).is_err() { + return Err(format!( + "The column {column} has the value {}, which does not fit in the \ + precision {precision} of its decimal type in the schema to read", + Decimal128Type::format_decimal( + value, + Decimal128Type::MAX_PRECISION, + *scale + ) + ) + .into()); + } + } + } + DataType::Struct(fields) => { + let mask: Vec<bool> = (0..data.len()).map(valid).collect(); + for (child, field) in data.child_data().iter().zip(fields) { + let name = format!("{column}.{}", field.name()); + check_values(child, field, &name, Some(&mask))?; + } + } + DataType::List(element) => { + let mask = elements(data, valid)?; + let name = format!("{column}.element"); + check_values(&data.child_data()[0], element, &name, Some(&mask))?; + } + DataType::Map(entries, _) => { + let DataType::Struct(fields) = entries.data_type() else { + return Err("Arrow map entries must be a struct".into()); + }; + let mask = elements(data, valid)?; + let entries = &data.child_data()[0]; + // Spark does not allow null keys. + let key = fields[0].as_ref().clone().with_nullable(false); + let name = format!("{column}.key"); + check_values(&entries.child_data()[0], &key, &name, Some(&mask))?; + let name = format!("{column}.value"); + check_values(&entries.child_data()[1], &fields[1], &name, Some(&mask))?; Review Comment: Done in 997f5702e1f0: `list_elements_and_map_values_respect_their_nullability` now also reads `[{"a": 1}, null]`, where the null slot spans an entry with a null key and a null value, and expects `batch_error(batch, &required)` to be `None`. Passing `None` instead of `Some(&mask)` at either call breaks it. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
