gengliangwang commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4589192989
########## sql/native/rust/src/stream.rs: ########## @@ -0,0 +1,1030 @@ +// 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))?; + } + _ => {} + } + Ok(()) +} + +/// Whether a type has values to check under it: a decimal, a field, an element, or a map value +/// that is not nullable, or a map, whose keys are never null. +fn needs_check(data_type: &DataType) -> bool { + let required = |field: &Field| !field.is_nullable() || needs_check(field.data_type()); + match data_type { + DataType::Decimal128(..) => true, + DataType::Struct(fields) => fields.iter().any(|field| required(field.as_ref())), + DataType::List(element) => required(element.as_ref()), + DataType::Map(..) => true, + _ => false, + } +} + +/// Whether each element of a list or map belongs to a value that `valid` accepts. +fn elements(data: &ArrayData, valid: impl Fn(usize) -> bool) -> Result<Vec<bool>> { + let offsets = data.buffer::<i32>(0); + let mut mask = vec![false; data.child_data()[0].len()]; + for index in 0..data.len() { + if valid(index) { + let start = usize::try_from(offsets[index])?; + let end = usize::try_from(offsets[index + 1])?; + mask.get_mut(start..end) + .ok_or("Arrow offsets exceed the length of their values")? + .fill(true); + } + } + Ok(mask) +} + +fn validate_layout(data: &ArrayData) -> Result<()> { + if data.offset() != 0 { + return Err(format!( + "Spark requires zero Arrow array offsets: {} has offset {}; normalize sliced arrays", + data.data_type(), + data.offset(), + ) + .into()); + } + for child in data.child_data() { + validate_layout(child)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::ffi::CStr; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use arrow_array::builder::{ + BooleanBuilder, Decimal128Builder, Int32Builder, ListBuilder, MapBuilder, + NullBufferBuilder, OffsetBufferBuilder, StringBuilder, StructBuilder, + }; + use arrow_array::ffi_stream::ArrowArrayStreamReader; + use arrow_array::{ + ArrayRef, BooleanArray, Decimal128Array, Int32Array, Int64Array, LargeStringArray, + MapArray, RecordBatch, RecordBatchReader, StringArray, + }; + use arrow_schema::{ArrowError, DataType, Field, Schema}; + + use super::*; + + struct Reader { + batches: std::vec::IntoIter<std::result::Result<RecordBatch, ArrowError>>, + panic_next: bool, + panic_drop: bool, + drops: Arc<AtomicUsize>, + } + + impl Iterator for Reader { + type Item = std::result::Result<RecordBatch, ArrowError>; + + fn next(&mut self) -> Option<Self::Item> { + assert!(!self.panic_next, "iterator failed"); + self.batches.next() + } + } + + impl Drop for Reader { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::SeqCst); + assert!(!self.panic_drop, "drop failed"); + } + } + + fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])) + } + + fn export_with(reader: Reader, expected: &SchemaRef) -> FFI_ArrowArrayStream { + // Test readers own all their state and cannot borrow a host context. + unsafe { super::export(Box::new(reader), expected) } + } + + fn export(reader: Reader) -> FFI_ArrowArrayStream { + export_with(reader, &schema()) + } + + fn reader_of(batches: Vec<RecordBatch>) -> Reader { + Reader { + batches: batches.into_iter().map(Ok).collect::<Vec<_>>().into_iter(), + panic_next: false, + panic_drop: false, + drops: Arc::default(), + } + } + + fn reader() -> Reader { + let values = Arc::new(Int64Array::from(vec![3, 5])); + reader_of(vec![RecordBatch::try_new(schema(), vec![values]).unwrap()]) + } + + /// Calls get_schema, which reads the first batch, and returns its error, if any. + fn first_batch_error(stream: &mut FFI_ArrowArrayStream) -> Option<String> { + let mut schema = FFI_ArrowSchema::empty(); + if unsafe { stream.get_schema.unwrap()(stream, &mut schema) } == 0 { + return None; + } + let error = unsafe { stream.get_last_error.unwrap()(stream) }; + Some( + unsafe { CStr::from_ptr(error) } + .to_str() + .unwrap() + .to_owned(), + ) + } + + fn batch_error(batch: RecordBatch, expected: &SchemaRef) -> Option<String> { + first_batch_error(&mut export_with(reader_of(vec![batch]), expected)) + } + + fn at_end(stream: &mut FFI_ArrowArrayStream) -> bool { + let mut array = FFI_ArrowArray::empty(); + let status = unsafe { stream.get_next.unwrap()(stream, &mut array) }; + status == 0 && array.is_released() + } + + /// Checks that a failed stream fails again, with the same error, instead of reporting the + /// end of its batches. + fn stays_failed(stream: &mut FFI_ArrowArrayStream, error: &str) { + let mut array = FFI_ArrowArray::empty(); + assert_ne!(unsafe { stream.get_next.unwrap()(stream, &mut array) }, 0); + let mut schema = FFI_ArrowSchema::empty(); + assert_ne!( + unsafe { stream.get_schema.unwrap()(stream, &mut schema) }, + 0 + ); + let again = unsafe { CStr::from_ptr(stream.get_last_error.unwrap()(stream)) }; + assert_eq!(again.to_str().unwrap(), error); + } + + #[test] + fn imported_batch_survives_early_stream_release() { + let reader = reader(); + let drops = reader.drops.clone(); + let mut stream = ArrowArrayStreamReader::try_new(export(reader)).unwrap(); + let batch = stream.next().unwrap().unwrap(); + drop(stream); + assert_eq!(drops.load(Ordering::SeqCst), 1); + assert_eq!(batch.num_rows(), 2); + let values = batch + .column(0) + .as_any() + .downcast_ref::<Int64Array>() + .unwrap(); + assert_eq!(values.values(), &[3, 5]); + } + + #[test] + fn empty_batch_is_not_eof() { + let mut reader = reader(); + let first = reader.batches.next().unwrap(); + reader.batches = vec![Ok(RecordBatch::new_empty(schema())), first].into_iter(); + let mut stream = ArrowArrayStreamReader::try_new(export(reader)).unwrap(); + assert_eq!(stream.next().unwrap().unwrap().num_rows(), 0); + assert_eq!(stream.next().unwrap().unwrap().num_rows(), 2); + assert!(stream.next().is_none()); + } + + #[test] + fn a_reader_without_batches_has_the_schema_to_read() { + let mut stream = ArrowArrayStreamReader::try_new(export(reader_of(vec![]))).unwrap(); + assert_eq!(stream.schema(), schema()); + assert!(stream.next().is_none()); + } + + #[test] + fn the_first_batch_determines_the_arrow_types_of_the_stream() { + // The schema to read has a Utf8 string, which the reader returns as LargeUtf8. + let expected = Arc::new(Schema::new(vec![Field::new("label", DataType::Utf8, true)])); + let actual = Arc::new(Schema::new(vec![Field::new( + "label", + DataType::LargeUtf8, + true, + )])); + let labels = Arc::new(LargeStringArray::from(vec!["a", "b"])); + let batch = RecordBatch::try_new(actual.clone(), vec![labels]).unwrap(); + let exported = export_with(reader_of(vec![batch]), &expected); + let mut stream = ArrowArrayStreamReader::try_new(exported).unwrap(); + assert_eq!(stream.schema(), actual); + let batch = stream.next().unwrap().unwrap(); + let labels = batch + .column(0) + .as_any() + .downcast_ref::<LargeStringArray>() + .unwrap(); + assert_eq!(labels.value(1), "b"); + assert!(stream.next().is_none()); + } + + #[test] + fn the_sdk_keeps_the_columns_of_the_schema_to_read_by_name() { + // The reader ignores pruning and returns all the columns of the source, in its order. + let all = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("flag", DataType::Boolean, false), + ])); + let ids = Arc::new(Int64Array::from(vec![3, 5])); + let flags = Arc::new(BooleanArray::from(vec![true, false])); + let batch = RecordBatch::try_new(all, vec![ids, flags]).unwrap(); + for (columns, rows) in [(vec!["flag", "id"], 2), (vec![], 2)] { + let fields: Vec<_> = columns + .iter() + .map(|name| match *name { + "id" => Field::new("id", DataType::Int64, false), + _ => Field::new("flag", DataType::Boolean, false), + }) + .collect(); + let expected = Arc::new(Schema::new(fields)); + let exported = export_with(reader_of(vec![batch.clone()]), &expected); + let mut stream = ArrowArrayStreamReader::try_new(exported).unwrap(); + assert_eq!(stream.schema(), expected); + let read = stream.next().unwrap().unwrap(); + assert_eq!(read.schema(), expected); + assert_eq!(read.num_rows(), rows, "{columns:?}"); + assert!(stream.next().is_none()); + } + } + + #[test] + fn the_sdk_resolves_the_columns_again_when_a_batch_reorders_them() { + let id = Field::new("id", DataType::Int64, false); + let flag = Field::new("flag", DataType::Boolean, false); + let flags = || Arc::new(BooleanArray::from(vec![true, false])); + let first = RecordBatch::try_new( + Arc::new(Schema::new(vec![id.clone(), flag.clone()])), + vec![Arc::new(Int64Array::from(vec![3, 5])), flags()], + ) + .unwrap(); + let second = RecordBatch::try_new( + Arc::new(Schema::new(vec![flag, id.clone()])), + vec![flags(), Arc::new(Int64Array::from(vec![7, 9]))], + ) + .unwrap(); + let expected = Arc::new(Schema::new(vec![id])); + let exported = export_with(reader_of(vec![first, second]), &expected); + let mut stream = ArrowArrayStreamReader::try_new(exported).unwrap(); + for ids in [vec![3, 5], vec![7, 9]] { + let read = stream.next().unwrap().unwrap(); + assert_eq!(read.schema(), expected); + let column = read.column(0).as_any().downcast_ref::<Int64Array>(); + assert_eq!(column, Some(&Int64Array::from(ids))); + } + assert!(stream.next().is_none()); + } + + #[test] + fn get_next_may_read_the_first_batch_before_get_schema() { + let mut stream = export(reader()); + let mut array = FFI_ArrowArray::empty(); + assert_eq!( + unsafe { stream.get_next.unwrap()(&mut stream, &mut array) }, + 0 + ); + assert_eq!(array.len(), 2); + let mut exported = FFI_ArrowSchema::empty(); + assert_eq!( + unsafe { stream.get_schema.unwrap()(&mut stream, &mut exported) }, + 0 + ); + assert_eq!(Schema::try_from(&exported).unwrap(), *schema()); + assert!(at_end(&mut stream)); + } + + #[test] + fn iterator_panics_and_nul_errors_become_stream_errors() { + let mut panicking = reader(); + panicking.panic_next = true; + let error = first_batch_error(&mut export(panicking)).unwrap(); + assert!(error.contains("iterator failed"), "{error}"); + + let mut failing = reader(); + failing.batches = vec![Err(ArrowError::ComputeError("bad\0value".into()))].into_iter(); + let error = first_batch_error(&mut export(failing)).unwrap(); + assert!(error.contains("bad\\0value"), "{error}"); + + // The error of a later batch is reported by get_next instead. + let mut failing = reader(); + let first = failing.batches.next().unwrap(); + let late = Err(ArrowError::ComputeError("late failure".into())); + failing.batches = vec![first, late].into_iter(); + let mut stream = ArrowArrayStreamReader::try_new(export(failing)).unwrap(); + assert_eq!(stream.next().unwrap().unwrap().num_rows(), 2); + let error = stream.next().unwrap().unwrap_err().to_string(); + assert!(error.contains("late failure"), "{error}"); + // The stream stays failed, with the same error. + assert_eq!(stream.next().unwrap().unwrap_err().to_string(), error); + } + + #[test] + fn iterator_and_drop_panics_do_not_escape_the_stream_boundary() { + let mut failing = reader(); + let drops = failing.drops.clone(); + failing.panic_next = true; + failing.panic_drop = true; + let error = first_batch_error(&mut export(failing)).unwrap(); + assert!(error.contains("iterator failed"), "{error}"); + assert_eq!(drops.load(Ordering::SeqCst), 1); + + let mut failing = reader(); + let drops = failing.drops.clone(); + failing.panic_drop = true; + drop(export(failing)); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_schema_mismatch_drops_the_reader() { + let reader = reader(); + let drops = reader.drops.clone(); + let expected = Arc::new(Schema::new(vec![Field::new("id", DataType::Utf8, false)])); + let mut stream = export_with(reader, &expected); + let error = first_batch_error(&mut stream).unwrap(); + assert!( + error.contains("does not match the schema to read"), + "{error}" + ); + stays_failed(&mut stream, &error); + drop(stream); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn logical_schema_comparison_accepts_equivalent_arrow_representations() { + let actual = Schema::new(vec![ + Field::new("text", DataType::LargeUtf8, true), + Field::new("bytes", DataType::BinaryView, true), + Field::new( + "time", + DataType::Timestamp(TimeUnit::Microsecond, Some("Europe/Paris".into())), + true, + ), + Field::new( + "nested", + DataType::Struct(vec![Field::new("text", DataType::Utf8View, true)].into()), + true, + ), + ]); + let expected = Schema::new(vec![ + Field::new("text", DataType::Utf8, false), + Field::new("bytes", DataType::Binary, false), + Field::new( + "time", + DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())), + false, + ), + Field::new( + "nested", + DataType::Struct(vec![Field::new("text", DataType::Utf8, false)].into()), + false, + ), + ]); + assert_eq!( + canonical_fields(actual.fields()).unwrap(), + canonical_fields(expected.fields()).unwrap() + ); + // A timestamp without a time zone remains a distinct Spark logical type. + assert_ne!( + canonical_type(&DataType::Timestamp(TimeUnit::Microsecond, None)).unwrap(), + canonical_type(&DataType::Timestamp( + TimeUnit::Microsecond, + Some("UTC".into()) + )) + .unwrap() + ); + } + + #[test] + fn unsupported_types_are_rejected_inside_nested_fields() { + let nested_types = [ + DataType::List(Arc::new(Field::new("item", DataType::UInt64, false))), + DataType::Struct( + vec![Field::new( + "dictionary", + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), + false, + )] + .into(), + ), + DataType::Map( + Arc::new(Field::new( + "entries", + DataType::Struct( + vec![ + Field::new("key", DataType::Utf8, false), + Field::new("value", DataType::Decimal256(40, 2), true), + ] + .into(), + ), + false, + )), + false, + ), + ]; + for data_type in nested_types { + let schema = Arc::new(Schema::new(vec![Field::new("nested", data_type, true)])); + assert!(validate_schema(&schema) + .unwrap_err() + .to_string() + .contains("unsupported Spark Arrow type")); + } + } + + #[test] + fn a_valid_sliced_boolean_inside_a_struct_is_rejected_before_export() { + let values = BooleanArray::from(vec![true, false, true]).slice(1, 2); + assert_eq!(values.to_data().offset(), 1); + let fields: Fields = vec![Field::new("flag", DataType::Boolean, false)].into(); + let nested = StructArray::new(fields.clone(), vec![Arc::new(values)], None); + let schema = Arc::new(Schema::new(vec![Field::new( + "nested", + DataType::Struct(fields), + false, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(nested)]).unwrap(); + let reader = reader_of(vec![batch]); + let drops = reader.drops.clone(); + // All arrays are valid, owned Arrow values, without a borrowed task context. + let mut stream = export_with(reader, &schema); + let error = first_batch_error(&mut stream).unwrap(); + assert!(error.contains("zero Arrow array offsets"), "{error}"); + assert!(error.contains("offset 1"), "{error}"); + stays_failed(&mut stream, &error); + drop(stream); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } + + #[test] + fn intervals_and_the_null_type_are_not_version_1_types() { + for data_type in [ + DataType::Null, + DataType::Duration(TimeUnit::Microsecond), + DataType::Interval(arrow_schema::IntervalUnit::YearMonth), + DataType::Interval(arrow_schema::IntervalUnit::MonthDayNano), + ] { + let schema = Arc::new(Schema::new(vec![Field::new("value", data_type, true)])); + assert!(validate_schema(&schema).is_err()); + } + } + + #[test] + fn nulls_must_respect_the_nullability_of_the_schema_to_read() { + let values = Arc::new(Int64Array::from(vec![Some(1), None])); + let nullable = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, true)])); + let required = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new(nullable.clone(), vec![values]).unwrap(); + let error = batch_error(batch.clone(), &required); + assert!(error.unwrap().contains("The column id has a null")); + assert_eq!(batch_error(batch, &nullable), None); + } + + #[test] + fn nested_nulls_are_allowed_only_under_a_null_parent() { + let required = Fields::from(vec![Field::new("flag", DataType::Boolean, false)]); + let nullable = Fields::from(vec![Field::new("flag", DataType::Boolean, true)]); + let schema = |fields: &Fields| { + Arc::new(Schema::new(vec![Field::new( + "nested", + DataType::Struct(fields.clone()), + true, + )])) + }; + fn flags(builder: &mut StructBuilder) -> &mut BooleanBuilder { + builder.field_builder::<BooleanBuilder>(0).unwrap() + } + for (parent_is_valid, rejected) in [(false, false), (true, true)] { + let mut builder = + StructBuilder::new(nullable.clone(), vec![Box::new(BooleanBuilder::new())]); + flags(&mut builder).append_value(true); + builder.append(true); + flags(&mut builder).append_null(); + builder.append(parent_is_valid); + let batch = + RecordBatch::try_new(schema(&nullable), vec![Arc::new(builder.finish())]).unwrap(); + let error = batch_error(batch, &schema(&required)); + assert_eq!(error.is_some(), rejected, "{error:?}"); + if let Some(error) = error { + assert!( + error.contains("The column nested.flag has a null"), + "{error}" + ); + } + } + } + + #[test] + fn list_elements_and_map_values_respect_their_nullability() { + let list_schema = |nullable| { + let element = Arc::new(Field::new("item", DataType::Int32, nullable)); + Arc::new(Schema::new(vec![Field::new( + "values", + DataType::List(element), + true, + )])) + }; + for (first, rejected) in [(Some(1), false), (None, true)] { + let mut builder = ListBuilder::new(Int32Builder::new()); + builder.values().append_option(first); + builder.append(true); + // The second list is null, so its null element does not count. + builder.values().append_null(); + builder.append(false); + let lists = Arc::new(builder.finish()); + let batch = RecordBatch::try_new(list_schema(true), vec![lists]).unwrap(); + let error = batch_error(batch, &list_schema(false)); + assert_eq!(error.is_some(), rejected, "{error:?}"); + if let Some(error) = error { + assert!( + error.contains("The column values.element has a null"), + "{error}" + ); + } + } + + let mut builder = MapBuilder::new(None, StringBuilder::new(), Int32Builder::new()); + builder.keys().append_value("a"); + builder.values().append_null(); + builder.append(true).unwrap(); + let map = builder.finish(); + let actual = Arc::new(Schema::new(vec![Field::new( + "map", + map.data_type().clone(), + true, + )])); + let entries = Fields::from(vec![ + Field::new("key", DataType::Utf8, false), + Field::new("value", DataType::Int32, false), + ]); + let entries = Arc::new(Field::new("entries", DataType::Struct(entries), false)); + let required = Arc::new(Schema::new(vec![Field::new( + "map", + DataType::Map(entries, false), + true, + )])); + let batch = RecordBatch::try_new(actual.clone(), vec![Arc::new(map)]).unwrap(); + let error = batch_error(batch.clone(), &required); + assert!(error.unwrap().contains("The column map.value has a null")); + assert_eq!(batch_error(batch, &actual), None); + + // [{"a": 1}, null], where the null map still spans an entry with a null key and a null + // value: neither counts, even though the schema to read declares both not nullable. + let batch = map_batch(vec![Some(1), None], &[1, 1], &[true, false]); + assert_eq!(batch_error(batch, &required), None); + } + + /// Builds a batch with one nullable column "map" over the keys ["a", null] and `values`, + /// with a map of each of `lengths` entries, null where `slots` is false. MapBuilder rejects + /// null keys, but a map whose key field is nullable can have them. + fn map_batch(values: Vec<Option<i32>>, lengths: &[usize], slots: &[bool]) -> RecordBatch { + let fields = Fields::from(vec![ + Field::new("key", DataType::Utf8, true), + Field::new("value", DataType::Int32, true), + ]); + let keys: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), None])); + let values: ArrayRef = Arc::new(Int32Array::from(values)); + let entries = StructArray::try_new(fields.clone(), vec![keys, values], None).unwrap(); + let entries_field = Arc::new(Field::new("entries", DataType::Struct(fields), false)); + let mut offsets = OffsetBufferBuilder::<i32>::new(lengths.len()); + for &length in lengths { + offsets.push_length(length); + } + let mut nulls = NullBufferBuilder::new(slots.len()); + nulls.append_slice(slots); + let (offsets, nulls) = (offsets.finish(), nulls.finish()); + let map = MapArray::try_new(entries_field, offsets, entries, nulls, false).unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new( + "map", + map.data_type().clone(), + true, + )])); + RecordBatch::try_new(schema, vec![Arc::new(map)]).unwrap() + } + + #[test] + fn map_keys_cannot_be_null_whatever_the_schema_to_read_declares() { + let batch = map_batch(vec![Some(1), Some(2)], &[2], &[true]); + let error = batch_error(batch.clone(), &batch.schema()).unwrap(); + assert!(error.contains("The column map.key has a null"), "{error}"); + } + + #[test] + fn decimal_values_must_fit_the_precision_of_the_schema_to_read() { + let schema = Arc::new(Schema::new(vec![Field::new( + "amount", + DataType::Decimal128(5, 2), + true, + )])); + let amounts = |values: Vec<Option<i128>>| -> ArrayRef { + let array = Decimal128Array::from(values); + Arc::new(array.with_precision_and_scale(5, 2).unwrap()) + }; + let fitting = amounts(vec![Some(12345), None, Some(-99999)]); + let batch = RecordBatch::try_new(schema.clone(), vec![fitting]).unwrap(); + assert_eq!(batch_error(batch, &schema), None); + let overflowing = amounts(vec![Some(12345), Some(123456)]); + let batch = RecordBatch::try_new(schema.clone(), vec![overflowing]).unwrap(); + let error = batch_error(batch, &schema).unwrap(); + assert!( + error.contains("The column amount has the value 1234.56"), + "{error}" + ); + assert!(error.contains("precision 5"), "{error}"); + } + + #[test] + fn decimal_values_under_a_null_parent_are_not_checked() { + let fields = Fields::from(vec![Field::new("amount", DataType::Decimal128(5, 2), true)]); + let schema = Arc::new(Schema::new(vec![Field::new( + "nested", + DataType::Struct(fields.clone()), + true, + )])); + for (parent_is_valid, rejected) in [(false, false), (true, true)] { + let amounts = Decimal128Builder::new().with_data_type(DataType::Decimal128(5, 2)); + let mut builder = StructBuilder::new(fields.clone(), vec![Box::new(amounts)]); + builder + .field_builder::<Decimal128Builder>(0) + .unwrap() + .append_value(123456); + builder.append(parent_is_valid); + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(builder.finish())]).unwrap(); + let error = batch_error(batch, &schema); + assert_eq!(error.is_some(), rejected, "{error:?}"); + if let Some(error) = error { + assert!(error.contains("nested.amount"), "{error}"); + } + } + } + + #[test] + fn a_batch_cannot_change_the_schema_of_the_stream() { + let mut reader = reader(); + let first = reader.batches.next().unwrap(); + let changed_schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); Review Comment: Done in 40fbaf065d48: Added `a_batch_cannot_change_the_arrow_encoding_of_a_spark_type`: a second batch with `LargeUtf8` after a first with `Utf8` fails with the "different schema" error, and the stream keeps failing with it. ########## sql/native/rust/src/stream.rs: ########## @@ -0,0 +1,1030 @@ +// 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( Review Comment: Done in 40fbaf065d48: The list nullability test now reads a `ListBuilder` batch, whose element is named "item", against a schema to read whose element is named "element". It still checks that the element's nullability is enforced. ########## sql/native/rust/src/bridge.rs: ########## @@ -0,0 +1,988 @@ +// 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. + +//! Driver-only handles of sources, scans, streams, and writes, and executor readers restored +//! from serialized values. + +use std::any::Any; +use std::collections::HashMap; +use std::ffi::CString; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use arrow_array::ffi_stream::FFI_ArrowArrayStream; +use arrow_schema::SchemaRef; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; + +use crate::write::{Batch, DriverWrite, DriverWriter}; +use crate::{ + abi, BatchWrite, Capabilities, CommitOffsetInfo, CreateInfo, DataSource, LatestOffsetInfo, + LimitSupport, MicroBatchInfo, MicroBatchStream, MicroBatchStreamInfo, PartitionReaderFactory, + ReadLimit, ReaderContext, Result, ScanBuilder, ScanInfo, ScanPlan, StreamingWrite, + StreamingWriteInfo, TaskContext, WriteInfo, WriteMode, +}; + +#[path = "stream.rs"] +pub(crate) mod stream; + +const STATE_VERSION: u32 = 1; + +type HandleMap<T> = Mutex<HashMap<i64, Arc<Mutex<T>>>>; + +/// One registry per loaded plugin. Provider code runs under a per-handle lock, +/// so independent sources, scans, and streams do not serialize behind a global lock. +pub struct Bridge<S: DataSource> { + next_handle: AtomicI64, + sources: HandleMap<SourceState<S>>, + // The builder of each scan, until Spark plans the scan. + scans: HandleMap<Option<S::ScanBuilder>>, + streams: HandleMap<S::MicroBatchStream>, + writers: HandleMap<Box<dyn DriverWrite>>, +} + +impl<S: DataSource> Default for Bridge<S> { + fn default() -> Self { + Self { + next_handle: AtomicI64::new(1), + sources: Mutex::new(HashMap::new()), + scans: Mutex::new(HashMap::new()), + streams: Mutex::new(HashMap::new()), + writers: Mutex::new(HashMap::new()), + } + } +} + +/// The partitions of a scan or a micro-batch, and the state of its reader: its factory. +pub struct EncodedPlan { + pub state: Vec<u8>, + pub partitions: Vec<Vec<u8>>, +} + +impl<S: DataSource> Bridge<S> { + // Whether the source implements each operation, whose native callbacks the SDK installs. + + pub const READ: bool = <S::ScanBuilder as ScanBuilder>::SUPPORTED; + + pub const MICRO_BATCH_READ: bool = <S::MicroBatchStream as MicroBatchStream>::SUPPORTED; + + pub const WRITE: bool = <S::BatchWrite as BatchWrite>::SUPPORTED; + + pub const STREAMING_WRITE: bool = <S::StreamingWrite as StreamingWrite>::SUPPORTED; + + const CAPABILITIES: Capabilities = Capabilities::implemented(&[ + (Capabilities::BATCH_READ, Self::READ), + (Capabilities::MICRO_BATCH_READ, Self::MICRO_BATCH_READ), + (Capabilities::BATCH_WRITE, Self::WRITE), + (Capabilities::STREAMING_WRITE, Self::STREAMING_WRITE), + ( + Capabilities::BATCH_TRUNCATE, + <S::BatchWrite as BatchWrite>::SUPPORTS_TRUNCATE, + ), + ( + Capabilities::STREAMING_TRUNCATE, + <S::StreamingWrite as StreamingWrite>::SUPPORTS_TRUNCATE, + ), + ]); + + fn insert<T>(&self, handles: &HandleMap<T>, value: T) -> Result<i64> { + let handle = self + .next_handle + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .map_err(|_| "native handle IDs exhausted")?; + lock(handles).insert(handle, Arc::new(Mutex::new(value))); + Ok(handle) + } + + pub fn create(&self, info: CreateInfo) -> Result<(i64, u64)> { + self.register_source(S::new(info)?) + } + + fn register_source(&self, source: S) -> Result<(i64, u64)> { + let capabilities = Self::effective(source.capabilities()); + let handle = self.insert( + &self.sources, + SourceState { + source, + capabilities, + }, + )?; + // Every stream supports admission control: its default read limit is all the + // available data unless it overrides MicroBatchStream::default_read_limit. + let admission_control = if capabilities.contains(Capabilities::MICRO_BATCH_READ) { + abi::ADMISSION_CONTROL + } else { + 0 + }; + Ok((handle, capabilities.bits() | admission_control)) + } + + /// Keeps the implemented operations of a declaration, so that a source can narrow its + /// operations but never add one, and each truncation only with its write. + fn effective(declared: Capabilities) -> Capabilities { + let mut capabilities = declared.intersection(Self::CAPABILITIES); + for (write, truncate) in [ + (Capabilities::BATCH_WRITE, Capabilities::BATCH_TRUNCATE), + ( + Capabilities::STREAMING_WRITE, + Capabilities::STREAMING_TRUNCATE, + ), + ] { + if !capabilities.contains(write) { + capabilities = capabilities.without(truncate); + } + } + capabilities + } + + pub fn schema(&self, handle: i64) -> Result<SchemaRef> { + let source = get(&self.sources, handle)?; + let schema = lock(&source).source.infer_schema()?; + stream::validate_schema(&schema)?; + Ok(schema) + } + + pub fn create_reader(&self, handle: i64, schema: SchemaRef) -> Result<i64> { + stream::validate_schema(&schema)?; + let source = get(&self.sources, handle)?; + let builder = { + let source = lock(&source); + require(source.capabilities, Capabilities::BATCH_READ, "batch reads")?; + source.source.new_scan(ScanInfo::new(schema))? + }; + self.insert(&self.scans, Some(builder)) + } + + pub fn push_limit(&self, handle: i64, limit: usize) -> Result<bool> { + let scan = get(&self.scans, handle)?; + let mut scan = lock(&scan); + Ok(builder(&mut scan)?.push_limit(limit)? == LimitSupport::Global) + } + + pub fn prune_columns(&self, handle: i64, columns: &[String]) -> Result<()> { + let scan = get(&self.scans, handle)?; + let mut scan = lock(&scan); + builder(&mut scan)?.prune_columns(columns) + } + + /// Plans a scan, which consumes its builder. + pub fn plan(&self, handle: i64) -> Result<EncodedPlan> { + let scan = get(&self.scans, handle)?; + let builder = lock(&scan) + .take() + .ok_or("the scan has already been planned")?; + encode_plan(builder.plan()?) + } + + pub fn close_reader(&self, handle: i64) -> Result<()> { + remove(&self.scans, handle); + Ok(()) + } + + pub fn create_stream_reader(&self, handle: i64, info: MicroBatchStreamInfo) -> Result<i64> { + stream::validate_schema(&info.schema)?; + let source = get(&self.sources, handle)?; + let stream = { + let source = lock(&source); + require( + source.capabilities, + Capabilities::MICRO_BATCH_READ, + "micro-batch streaming reads", + )?; + source.source.new_micro_batch_stream(info)? + }; + self.insert(&self.streams, stream) + } + + pub fn initial_offset(&self, handle: i64) -> Result<String> { + let stream = get(&self.streams, handle)?; + let offset = lock(&stream).initial_offset()?; + encode_offset(&offset) + } + + pub fn default_read_limit(&self, handle: i64) -> Result<ReadLimit> { + let stream = get(&self.streams, handle)?; + let limit = lock(&stream).default_read_limit(); + limit + } + + /// Decodes the offsets of a request, and encodes the latest offset. + pub fn latest_offset(&self, handle: i64, info: LatestOffsetInfo<String>) -> Result<String> { + let stream = get(&self.streams, handle)?; + let info = LatestOffsetInfo { + start: decode_offset(&info.start)?, + limit: info.limit, + run_end: info.run_end.as_deref().map(decode_offset).transpose()?, + }; + let offset = lock(&stream).latest_offset(info)?; + encode_offset(&offset) + } + + pub fn stream_partitions(&self, handle: i64, start: &str, end: &str) -> Result<EncodedPlan> { + let stream = get(&self.streams, handle)?; + let info = MicroBatchInfo::new(decode_offset(start)?, decode_offset(end)?); + let plan = lock(&stream).plan(info)?; + encode_plan(plan) + } + + pub fn commit_offset(&self, handle: i64, end: &str) -> Result<()> { + let stream = get(&self.streams, handle)?; + let info = CommitOffsetInfo::new(decode_offset(end)?); + let result = lock(&stream).commit(info); + result + } + + pub fn close_stream_reader(&self, handle: i64) -> Result<()> { + remove(&self.streams, handle); + Ok(()) + } + + /// Creates a batch write, or the write of a micro-batch of the streaming query `query_id`, + /// with the state of its task writers. + pub fn create_writer( + &self, + handle: i64, + schema: SchemaRef, + mode: WriteMode, + query_id: Option<String>, + ) -> Result<(i64, Vec<u8>)> { + stream::validate_schema(&schema)?; + let source = get(&self.sources, handle)?; + let (writer, state) = { + let source = lock(&source); + let capabilities = source.capabilities; + let truncate = mode == WriteMode::Truncate; + match query_id { + None => { + require(capabilities, Capabilities::BATCH_WRITE, "batch writes")?; + if truncate { + let overwrite = "the save mode overwrite"; + require(capabilities, Capabilities::BATCH_TRUNCATE, overwrite)?; + } + let write = source.source.new_write(WriteInfo::new(schema, mode))?; + DriverWriter::create(Batch(write))? + } + Some(query_id) => { + require( + capabilities, + Capabilities::STREAMING_WRITE, + "streaming writes", + )?; + if truncate { + let complete = "the output mode complete"; + require(capabilities, Capabilities::STREAMING_TRUNCATE, complete)?; + } + let info = StreamingWriteInfo::new(schema, mode, query_id); + let write = source.source.new_streaming_write(info)?; + DriverWriter::create(write)? + } + } + }; + Ok((self.insert(&self.writers, writer)?, state)) + } + + pub fn commit(&self, handle: i64, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()> { + let writer = get(&self.writers, handle)?; + let result = lock(&writer).commit(epoch_id, messages); + result + } + + pub fn abort(&self, handle: i64, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()> { + let writer = get(&self.writers, handle)?; + let result = lock(&writer).abort(epoch_id, messages); + result + } + + pub fn close_writer(&self, handle: i64) -> Result<()> { + remove(&self.writers, handle); + Ok(()) + } + + pub fn close_source(&self, handle: i64) -> Result<()> { + remove(&self.sources, handle); + Ok(()) + } +} + +/// Opens the executor reader of a partition with factory `F`, using only serialized values. +/// No source, scan, stream, or driver handle registry is created or consulted. +/// +/// # Safety +/// `task` must satisfy TaskContext::from_raw and remain valid until the +/// returned stream is released. The stream's consumer must follow the +/// Arrow C Stream ownership protocol and keep the plugin loaded. +pub unsafe fn open_reader<F: PartitionReaderFactory>( + task: *const abi::SparkDsTaskContext, + schema: SchemaRef, + state: &[u8], + partition: &[u8], +) -> Result<FFI_ArrowArrayStream> { + stream::validate_schema(&schema)?; + let factory: F = decode(state)?; + let (task, partition_index) = unsafe { TaskContext::from_raw(task)? }; + let context = ReaderContext::new(schema.clone(), partition_index, task); + let reader = factory.open(decode(partition)?, context)?; + Ok(unsafe { stream::export(reader, &schema) }) +} + +fn require(capabilities: Capabilities, capability: Capabilities, operation: &str) -> Result<()> { + if capabilities.contains(capability) { + Ok(()) + } else { + Err(format!("source does not support {operation}").into()) + } +} + +/// The builder of a scan that is not planned yet. +fn builder<B>(scan: &mut Option<B>) -> Result<&mut B> { + scan.as_mut() + .ok_or_else(|| "the scan has already been planned".into()) +} + +/// Encodes the factory of a plan, as the state of its reader, and each of its partitions. +fn encode_plan<F: PartitionReaderFactory>(plan: ScanPlan<F>) -> Result<EncodedPlan> { + Ok(EncodedPlan { + state: encode(&plan.factory)?, + partitions: plan.partitions.iter().map(encode).collect::<Result<_>>()?, + }) +} + +fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { + // A provider panic becomes an ABI error. Recover the lock so close can + // still remove and release the handle after that failed call. + mutex.lock().unwrap_or_else(|error| error.into_inner()) +} + +fn get<T>(handles: &HandleMap<T>, handle: i64) -> Result<Arc<Mutex<T>>> { + lock(handles) + .get(&handle) + .cloned() + .ok_or_else(|| format!("unknown or closed native handle: {handle}").into()) +} + +fn remove<T>(handles: &HandleMap<T>, handle: i64) { + let value = lock(handles).remove(&handle); + // Provider destructors run after releasing the registry lock. Repeated + // closes are harmless, and IDs are never reused. + drop_provider(value); +} + +struct SourceState<S> { + source: S, + capabilities: Capabilities, +} + +/// Offsets are compact JSON on a single line, which Spark stores in the checkpoint as they +/// are, so they have no envelope: the library owns their format. +fn encode_offset<T: Serialize>(offset: &T) -> Result<String> { + Ok(serde_json::to_string(offset)?) +} + +fn decode_offset<T: DeserializeOwned>(json: &str) -> Result<T> { + serde_json::from_str(json) + .map_err(|error| format!("cannot decode the offset {json}: {error}").into()) +} + +/// The state of a reader or a writer, the partitions and the commit messages are MessagePack +/// in a versioned envelope. MessagePack is self-describing, and the SDK writes structs as maps +/// with the names of their fields, so the serde attributes that need them, such as `untagged`, +/// `flatten` and `default`, work, and floats, including NaN and the infinities, round-trip as +/// they are. A `Vec<u8>` stays a sequence: serde buffers the values of `untagged` and `flatten` +/// before deserializing them, and its buffer cannot read MessagePack binary as a sequence. +/// These values never outlive the application, and the same build of the library reads them, +/// so the format is an implementation detail; see the README. +#[derive(Serialize, Deserialize)] +struct Envelope<T> { + version: u32, + value: T, +} + +pub(crate) fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>> { + let mut bytes = Vec::new(); + let mut serializer = rmp_serde::Serializer::new(&mut bytes).with_struct_map(); + Envelope { + version: STATE_VERSION, + value, + } + .serialize(&mut serializer)?; + Ok(bytes) +} + +pub(crate) fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> { + let envelope: Envelope<T> = rmp_serde::from_slice(bytes)?; + if envelope.version != STATE_VERSION { + return Err(format!("unsupported native state version: {}", envelope.version).into()); + } + Ok(envelope.value) +} + +pub(crate) fn provider_call<T>( + action: impl FnOnce() -> Result<T>, +) -> std::result::Result<T, String> { + catch_unwind(AssertUnwindSafe(|| { + action().map_err(|error| describe(&*error)) + })) + .unwrap_or_else(|payload| Err(panic_message(payload))) +} + +pub(crate) fn drop_provider<T>(value: T) { + // Close has no error channel and must never unwind across the native ABI, so log the panic. + if let Err(payload) = catch_unwind(AssertUnwindSafe(|| drop(value))) { + log::warn!("Ignoring a panic during a drop: {}", panic_message(payload)); + } +} + +/// The message of an error followed by those of its sources, which `Display` of many +/// errors, such as those with added context, omits. +pub(crate) fn describe(error: &(dyn std::error::Error + 'static)) -> String { + let mut message = error.to_string(); + let mut source = error.source(); + while let Some(cause) = source { + let cause_message = cause.to_string(); + if !message.contains(&cause_message) { + message.push_str(": "); + message.push_str(&cause_message); + } + source = cause.source(); + } + message +} + +pub(crate) fn panic_message(payload: Box<dyn Any + Send>) -> String { + let message = if let Some(message) = payload.downcast_ref::<String>() { + message.clone() + } else if let Some(message) = payload.downcast_ref::<&str>() { + (*message).to_owned() + } else { + // An arbitrary panic payload can itself panic when dropped. + std::mem::forget(payload); Review Comment: Done in 40fbaf065d48: Added `non_string_panic_payloads_do_not_escape`. It checks that `provider_call` returns the non-string message for `panic_any(42)` and for a payload that panics when dropped, and that `drop_provider` does not unwind for a value whose drop panics with such a payload. ########## examples/src/main/rust/native-data-source/README.md: ########## @@ -0,0 +1,163 @@ +<!-- +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. +--> + +# Rust native range data source + +This example implements batch and micro-batch streaming reads using the +[Rust native data source SDK][sdk]. +The connector in [src/lib.rs](src/lib.rs) exports `rust_sdk_range` through the SDK's +`export_data_source!(RangeSource)` macro. The macro exports the C entry point +`spark_ds_init`; the connector does not use JNI, raw pointers, or unsafe code. + +The example targets version 1 of the C ABI of native data sources, `spark_datasource.h`, which +Spark 4.4.0 introduces. The SDK and example build without Spark or a JVM. Running the Spark smoke +script requires a distribution with native data sources and Java 22 or later on the driver and +executors. The JNI SDK prototype in PR #59442 targets a different interface. + +Naming `RangeScan` as the `ScanBuilder` and `RangeStream` as the `MicroBatchStream`, with +`Unsupported` writes, derives the `BATCH_READ` and `MICRO_BATCH_READ` capabilities and the native +mask `SPARK_DS_BATCH_READ | SPARK_DS_MICRO_BATCH_READ | SPARK_DS_ADMISSION_CONTROL` (`67`), +since every stream supports admission control; the connector does not maintain a separate +capability list. Connectors can narrow their operations through `DataSource::capabilities()` +based on options. This example does not implement writes. The companion +[file sink](../native-data-sink/README.md) demonstrates batch append and overwrite, and +exactly-once streaming writes. +During analysis, Spark creates and closes a source with the table options to inspect its +capabilities. It exposes `BATCH_WRITE` and `TRUNCATE` to Data Source V2 only when the source +declares `BATCH_WRITE` and `BATCH_TRUNCATE`, so this example rejects batch append and overwrite +before evaluating their input. +The framework still reports the Data Source V2 flags `BATCH_READ`, `MICRO_BATCH_READ`, and +`STREAMING_WRITE` to keep operations on the V2 path instead of falling back to V1. These routing +flags do not add native capabilities: each operation checks the native mask again with its own +options. A source created just for capability discovery is closed without creating a scan. + +## Data and options + +| Column | Spark type | Value | +| --- | --- | --- | +| `id` | `BIGINT`, non-null | Integers in `[start, end)` | +| `label` | `STRING`, non-null | `row-{id}`, such as `row-13` | + +| Option | Default | Meaning | +| --- | --- | --- | +| `start` | `0` | Inclusive start, as a signed 64-bit integer | +| `end` | `100` | Exclusive end; must be at least `start` | +| `numpartitions` | `2` | Maximum number of partitions; from 1 to 100000 | +| `batchsize` | `1024` | Maximum rows per Arrow batch; from 1 to 1000000 | +| `maxRowsPerTrigger` | none | Maximum rows per micro-batch of a streaming read; must be positive | + +Spark normalizes option names to lower case. Unknown options are rejected. + +Spark pushes a limit only to a scan whose rows it does not filter, and evaluates filters after +reading, since version 1 of the ABI does not push them down. The connector applies a global Review Comment: Done in 40fbaf065d48: The Range README now says that Spark pushes no filter down because the SDK does not expose the `push_domains` of version 1 of the ABI yet. ########## examples/src/main/rust/native-data-source/src/lib.rs: ########## @@ -0,0 +1,631 @@ +// 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. + +//! A deterministic range source: `id` in [start, end), and `label = "row-{id}"`. +//! All C ABI and Arrow C Stream plumbing is supplied by the SDK's export macro. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use arrow_array::StringArray; +use arrow_array::{ArrayRef, Int64Array, RecordBatch, RecordBatchOptions}; +use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_datasource::{ + CreateInfo, DataSource, LatestOffsetInfo, LimitSupport, MicroBatchInfo, MicroBatchStream, + MicroBatchStreamInfo, Options, PartitionReader, PartitionReaderFactory, ReadLimit, + ReaderContext, Result, ScanBuilder, ScanInfo, ScanPlan, Unsupported, +}; + +// The largest values of numPartitions and batchSize. +const MAX_PARTITIONS: usize = 100_000; +const MAX_BATCH_SIZE: usize = 1_000_000; + +pub struct RangeSource { + start: i64, + end: i64, + num_partitions: usize, + batch_size: usize, + max_rows_per_trigger: Option<u64>, +} + +pub struct RangeScan { + start: i64, + end: i64, + num_partitions: usize, + limit: Option<usize>, + factory: RangeReaderFactory, +} + +/// Reader configuration travels to each executor; it contains no live objects. +/// Spark passes the columns to read to the reader, so the factory omits them. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RangeReaderFactory { + batch_size: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RangePartition { + start: i64, + end: i64, +} + +/// A streaming read of the range. The range is fixed, so all its rows are available when +/// the query starts: the first micro-batch reads them, unless `maxRowsPerTrigger` limits each +/// micro-batch, and later ones find no new data. +pub struct RangeStream { + start: i64, + end: i64, + num_partitions: usize, + max_rows_per_trigger: Option<u64>, + factory: RangeReaderFactory, +} + +/// The offset of a streaming read: the next row to read. Spark stores it in the checkpoint +/// as `{"next":13}`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct RangeOffset { + next: i64, +} + +impl DataSource for RangeSource { + type ScanBuilder = RangeScan; + type MicroBatchStream = RangeStream; + // A read-only source. + type BatchWrite = Unsupported; + type StreamingWrite = Unsupported; + + fn new(info: CreateInfo) -> Result<Self> { + let options = info.options; + for key in options.keys() { + if !matches!( + key.as_str(), + "start" | "end" | "numpartitions" | "batchsize" | "maxrowspertrigger" + ) { + return Err(format!("Unknown range option: {key}").into()); + } + } + let start = option(&options, "start", 0_i64)?; + let end = option(&options, "end", 100_i64)?; + let num_partitions = option(&options, "numpartitions", 2_usize)?; + let batch_size = option(&options, "batchsize", 1024_usize)?; + let max_rows_per_trigger = options + .get("maxrowspertrigger") + .map(|_| option(&options, "maxrowspertrigger", 0_u64)) + .transpose()?; + if end < start { + return Err("end must be greater than or equal to start".into()); + } + if num_partitions == 0 || batch_size == 0 || max_rows_per_trigger == Some(0) { + return Err("numPartitions, batchSize and maxRowsPerTrigger must be positive".into()); + } + // A failed allocation aborts the process, so bound the sizes that the reads allocate. + if num_partitions > MAX_PARTITIONS || batch_size > MAX_BATCH_SIZE { + return Err(format!( + "numPartitions must be at most {MAX_PARTITIONS}, and batchSize at most \ + {MAX_BATCH_SIZE}" + ) + .into()); + } + Ok(Self { + start, + end, + num_partitions, + batch_size, + max_rows_per_trigger, + }) + } + + fn infer_schema(&self) -> Result<SchemaRef> { + output_schema(&["id".into(), "label".into()]) + } + + fn new_scan(&self, info: ScanInfo) -> Result<Self::ScanBuilder> { + read_columns(&info.schema)?; + Ok(RangeScan { + start: self.start, + end: self.end, + num_partitions: self.num_partitions, + limit: None, + factory: RangeReaderFactory { + batch_size: self.batch_size, + }, + }) + } + + fn new_micro_batch_stream(&self, info: MicroBatchStreamInfo) -> Result<Self::MicroBatchStream> { + read_columns(&info.schema)?; + Ok(RangeStream { + start: self.start, + end: self.end, + num_partitions: self.num_partitions, + max_rows_per_trigger: self.max_rows_per_trigger, + factory: RangeReaderFactory { + batch_size: self.batch_size, + }, + }) + } +} + +impl PartitionReaderFactory for RangeReaderFactory { + type Partition = RangePartition; + + fn open<'task>( + &self, + partition: RangePartition, + context: ReaderContext<'task>, + ) -> Result<PartitionReader<'task>> { + let batch_size = self.batch_size; + if batch_size == 0 || partition.start > partition.end { + return Err("Invalid serialized range plan".into()); + } + // The schema to read has the columns that the query needs, in order, with the + // types that the scan validated. + let schema = context.schema; + let columns: Vec<String> = schema.fields().iter().map(|f| f.name().clone()).collect(); + output_schema(&columns)?; + let task = context.task; + let mut current = partition.start; + let batches = std::iter::from_fn(move || { + if current == partition.end { + return None; + } + if task.is_interrupted() { + current = partition.end; + return Some(Err(ArrowError::ComputeError( + "Range read was cancelled".into(), + ))); + } + let next = + (i128::from(current) + batch_size as i128).min(i128::from(partition.end)) as i64; + let num_rows = (i128::from(next) - i128::from(current)) as usize; + let arrays: Vec<ArrayRef> = columns + .iter() + .map(|column| match column.as_str() { + "id" => Arc::new(Int64Array::from_iter_values(current..next)) as ArrayRef, + "label" => Arc::new(StringArray::from_iter_values( + (current..next).map(|id| format!("row-{id}")), + )) as ArrayRef, + _ => unreachable!("column names were validated before reading"), + }) + .collect(); + current = next; + // Explicit row counts also preserve COUNT(*) with a zero-column projection. + Some(RecordBatch::try_new_with_options( + Arc::clone(&schema), + arrays, + &RecordBatchOptions::new().with_row_count(Some(num_rows)), + )) + }); + Ok(Box::new(batches)) + } +} + +// The readers get the columns to read in their context, so the scan does not prune columns. +impl ScanBuilder for RangeScan { + type Factory = RangeReaderFactory; + + fn push_limit(&mut self, limit: usize) -> Result<LimitSupport> { + self.limit = Some(limit); + Ok(LimitSupport::Global) + } + + fn plan(self) -> Result<ScanPlan<RangeReaderFactory>> { + // Apply a global limit by shortening the range, then split it. + let lower = i128::from(self.start); + let upper = i128::from(self.end); + let upper = self + .limit + .map_or(upper, |limit| upper.min(lower + limit as i128)); + let partitions = split(lower, upper, self.num_partitions); + Ok(ScanPlan::new(self.factory, partitions)) + } +} + +impl MicroBatchStream for RangeStream { + type Offset = RangeOffset; + // Micro-batches are read as batch scans are. + type Factory = RangeReaderFactory; + + fn initial_offset(&mut self) -> Result<RangeOffset> { + Ok(RangeOffset { next: self.start }) + } + + fn default_read_limit(&self) -> Result<ReadLimit> { + Ok(self + .max_rows_per_trigger + .map_or(ReadLimit::AllAvailable, ReadLimit::MaxRows)) + } + + fn latest_offset(&mut self, info: LatestOffsetInfo<RangeOffset>) -> Result<RangeOffset> { + // The offsets of a checkpoint may come from a query with other options. Reject them + // here, before Spark logs the latest offset, which it would plan again on restart. + if info.start.next < self.start || info.start.next > self.end { Review Comment: Done in 40fbaf065d48: `a_stream_plans_micro_batches_between_json_offsets` now checks that `{"next":5}`, below the start 10, is rejected by `latest_offset` and by `plan` (to `{"next":12}`), each with the error that names the range. ########## sql/native/rust/README.md: ########## @@ -0,0 +1,570 @@ +<!-- +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. +--> + +# Rust native data source SDK prototype + +This experimental SDK implements **batch and micro-batch streaming reads, with admission +control, and batch and streaming writes** over version 1 of the C ABI of native data sources, +[`spark_datasource.h`][header], which Spark 4.4.0 introduces. Spark calls the library through +the Java Foreign Function and Memory (FFM) API, so running a library in Spark requires Java 22 +or newer on the driver and executors. The [guide of native data sources][guide] describes the +ABI. + +The Rust and C tests run independently of Spark and Java. The workspace is not +part of Maven/SBT and introduces no Rust requirement for building Spark. This is +an API prototype, not a compatibility commitment. + +The crate, `spark-datasource`, after `spark_datasource.h`, is not published yet: depend on it +with a path dependency on a Spark source tree, as the examples do, until SPARK-61307 publishes +it to crates.io. It is versioned on its own, from 0.x, and may need a breaking release in any +release of Spark: for a new major version of Arrow, whose types it exposes, or for a new kind +of operation, which adds an associated type to `DataSource` that every connector must name. +Growth within an operation can preserve Rust source compatibility, for example by adding +fields to non-exhaustive input structs under the conditions described below. The crate +supports version 1 of the ABI, which Spark supports from 4.4.0 in all the releases of Spark 4. + +The API uses the types of Arrow 58, such as `RecordBatch`, `SchemaRef`, and `ArrowError`, so +a connector must use the same major version of Arrow: the SDK re-exports the crates as +`spark_datasource::arrow_array` and `spark_datasource::arrow_schema`. Upgrading the +major version of Arrow is a breaking change of the SDK. + +The [Range connector][range] is a separate workspace member under +`examples/src/main/rust/native-data-source`, with a C integration test, packaging +helper, and Spark smoke script. The [file sink example][sink] is a separate write-only +connector. All crates share this directory's lockfile and `target` directory. Cargo commands +select the SDK by default; use `--workspace` to include the examples. + +## Connector API and lifecycle + +A connector implements [`DataSource`](src/lib.rs) for construction, schema discovery, +its operations, and optional capability restrictions. `DataSource::new` receives a +`CreateInfo` with the name of the data source and its options. Spark can create and +immediately drop a source just to discover capabilities; schema inference or an +operation need not follow. + +Four associated types name the operations that the source implements, and +`Unsupported` stands for one that it does not implement: + +```rust +impl DataSource for RangeSource { + type ScanBuilder = RangeScan; // batch reads, created by new_scan + type MicroBatchStream = RangeStream; // streaming reads, by new_micro_batch_stream + type BatchWrite = Unsupported; // no batch writes + type StreamingWrite = Unsupported; // no streaming writes + // new, infer_schema, new_scan, and new_micro_batch_stream +} +``` + +Read support uses three pieces: + +* `DataSource::new_scan`: create an independent scan builder from a `ScanInfo`, which + carries the schema to read. +* `ScanBuilder`: negotiate the limit and the columns to read, then consume itself + in `plan()` to return a typed `ScanPlan<Factory>`. +* `PartitionReaderFactory`: serialize executor configuration and open one lazy reader, + an iterator of Arrow batches, from a typed partition and a `ReaderContext`, which + carries the schema to read, the index of the partition in its plan, and a borrowed + `TaskContext`. + +Streaming reads reuse the executor side: `DataSource::new_micro_batch_stream` creates a +`MicroBatchStream` from a `MicroBatchStreamInfo`, which carries the columns to read and the +location of the checkpoint of the source, and the stream plans each micro-batch as a +`ScanPlan` of a `PartitionReaderFactory`; see +[Streaming reads and writes](#streaming-reads-and-writes). + +Write support is independent: a write-only connector sets `ScanBuilder` and +`MicroBatchStream` to `Unsupported` and implements `DataSource::new_write`, `BatchWrite`, +`DataWriterFactory`, and `DataWriter`. Streaming writes add +`DataSource::new_streaming_write` and `StreamingWrite`, with the same task writers. The +write lifecycle is described below. + +The inputs of these methods are `#[non_exhaustive]` structs: `*Info` structs on the driver +(`CreateInfo`, `ScanInfo`, `MicroBatchStreamInfo`, `LatestOffsetInfo`, `MicroBatchInfo`, +`CommitOffsetInfo`, `WriteInfo`, `CommitInfo`, `AbortInfo`, `StreamingWriteInfo`, +`StreamingCommitInfo`, and `StreamingAbortInfo`), `*Context` structs, which carry the live +`TaskContext`, on the executors (`ReaderContext` and `WriterContext`), and `HostInfo`, which +`DataSource::init` receives in every JVM that loads the library, executors included. Fields +may be added to them: construct them with `new`, as in tests, or `HostInfo` with +`HostInfo::default()` and then set its fields, and destructure them with `..`. +`ScanPlan` has a constructor for the same reason. The methods whose function of the header +passes nothing but the size of its info struct yet take no struct: `ScanBuilder::plan`, +`MicroBatchStream::initial_offset`, and the `commit` and `abort` of `DataWriter`. A field +added there would be a breaking change of the SDK, which its 0.x version allows. + +The factory and partition types implement `Serialize` and `Deserialize`, as the commit +messages of writes do. The SDK encodes them with serde in MessagePack, a self-describing binary +format in which structs are maps with the names of their fields, so the serde attributes that +need them, such as `untagged`, `flatten` and `default`, work, including on byte vectors, and +floats, including NaN and the infinities, round-trip as they are. Offsets are JSON instead, +since Spark stores them as text: see [Streaming reads and writes](#streaming-reads-and-writes). +Connections, pointers, and open readers remain in their creating process. +Include a snapshot identifier in the factory or partitions when retrying a task +must read the same snapshot. Several attempts of a task may open readers of the same +partition at the same time, so a reader must not take a resource that another attempt needs +exclusively, and a `ScanBuilder`, which Spark may drop late, must not hold one until Drop. + +```text +Driver: + DataSource::new_scan -> ScanBuilder -> ScanPlan { factory, partitions } + | | + mutable negotiation immutable serialized descriptors + | +Executor, per task: v + restored factory + partition + ReaderContext -> Arrow reader -> Arrow C Stream +``` + +The Rust API maps to the framework's driver-only `ColumnarBatchPlanner` and its +`ColumnarPlannedBatch` containing a serializable `PartitionReaderFactory`. +`ColumnarScanBuilder.build()` builds a single scan and transfers planner +ownership; it does not plan partitions. `ColumnarBatchScan` plans on the first +request for partitions or a reader factory and caches success or failure. + +For a native source, `NativeBatchPlanner` pushes the limit and the columns to read, +each at most once and in this order, then calls `partitions` once, which returns the +partitions and the state of the reader, and closes the native planner handle. The Rust +`ScanBuilder::plan()` consumes its builder in that call, and the SDK encodes the factory +as the state. After a call fails, Spark calls no other function on the handle than its +close function. Batch planner creation remains lazy for scans that do not read in batch. + +The JVM's `NativePartitionReaderFactory` carries only the library location, +source name, read schema, and serialized state. The native executor `read` entry +point gets the kind of the read, batch or micro-batch, and the schema to read with +the state and the partition, so it restores the Rust factory from those bytes without +creating or accessing the driver registry, and passes the schema to the reader in +`ReaderContext`. Closing the driver handles cannot invalidate factory or partition +bytes already copied to Spark, including for retried tasks. + +`ReaderContext::partition_index` is the partition's index in its scan or micro-batch's plan, +not the Spark task's partition ID. One task can read several source partitions, for example +after a coalesce or union, and different scans can reuse the same index. The task's stage +and attempt identifiers are in `ReaderContext::task`; `task_attempt_id()` identifies an +attempt within the Spark application. For writers, `WriterContext::partition_id` is the +Spark task's partition ID and the position of its winning commit message. `TaskContext` +does not expose a partition ID, since the ABI does not supply the task's partition ID for +readers. + +The reader owns its executor resources and cannot borrow its temporary factory. +It may borrow `TaskContext` until the returned Arrow stream is released. Every host +provides the task IDs of version 1 of the ABI, so the SDK rejects a task context shorter +than in Spark 4.4.0, as it rejects the info structures and the read limit that Spark passes to +the calls when they are shorter. It reads a field that a later release appends to one of them +only when Spark passes it, so a connector built with a later version of the SDK still runs on +4.4.0. `is_interrupted()` checks +Spark's live cancellation callback, not a snapshot of its initial value; for a reader, it +is also true once the task ended. Check it during long operations; blocking I/O still +requires timeouts. `TaskContext::for_testing()`, with its `with_*` methods and +`interrupted_by`, builds a context with chosen IDs and an optional interruption flag for +tests outside Spark. + +Export the source from the connector's `cdylib` crate: + +```rust +spark_datasource::export_data_source!(RangeSource); +``` + +The macro exports only `spark_ds_init` and returns Spark's versioned function +table. The connector uses safe Rust traits without C pointers. Rust trait objects +never cross the binary boundary between libraries. + +`DataSource::init` runs once in each JVM when Spark loads the library, with the +Spark version in `HostInfo`; a failure prevents Spark from using the library and is +logged. The macros of the `log` crate, which the SDK re-exports as +`spark_datasource::log`, write to the driver or executor log through Spark from any +thread, including in the library's dependencies, and drop messages outside Spark, such +as in unit tests. The SDK sets the level of the `log` crate to that of the log of Spark, +which it asks with `SparkDsHost.is_log_enabled` when Spark loads the library and when an +operation or a task starts, so it also follows a level that changes while Spark runs. + +A source that cannot infer its schema, such as a sink of any input, sets +`DataSource::INFERS_SCHEMA` to false. The SDK then leaves the native `schema` +function unset, so Spark requires a user-specified schema and reports its standard +error without one. + +A library that implements several data sources is installed or listed in its +package under each of their names. Spark passes the name in `CreateInfo::name`, so +one exported `DataSource` can choose the source to create; the macro exports a +single Rust type per library. Its four associated types are shared by all of its sources: +when they have different scan builders, factories, partitions, offsets, or messages, the +library wraps them in enums whose variants delegate to the types of each source. + +The implementation separates public connector traits, driver handle state in +`bridge.rs`, Arrow ownership in `stream.rs`, the writers in `write.rs`, C bindings in +`abi.rs`, and the function table in `export.rs`. The macro reaches them through a +hidden `__private` module, which is not part of the API. + +## Source capabilities + +The associated types of `DataSource` determine the operations of the source: batch +reads unless `ScanBuilder` is `Unsupported`, micro-batch reads unless `MicroBatchStream` +is, batch writes unless `BatchWrite` is, and streaming writes unless `StreamingWrite` is. +The SDK installs the native callbacks of these operations, leaves the others null, and +derives the default capability set from them, so the macro takes only the source type. +A `BatchWrite` or a `StreamingWrite` opts into truncation with +`const SUPPORTS_TRUNCATE: bool = true`, which declares `BATCH_TRUNCATE`, for the save mode +"overwrite" of a batch write, or `STREAMING_TRUNCATE`, for the output mode "complete" of a +streaming write. Its `new_*` method then gets `WriteMode::Truncate` for them; without it +the write only appends. Every stream also declares the native capability +`SPARK_DS_ADMISSION_CONTROL`, whose default read limit, all the available data, reads as +a stream without it does. The macro also rejects a library built with `panic = "abort"`, +because the SDK can report a panic as an error only when it unwinds. + +Most connectors do not implement `capabilities`. A connector can restrict the +supported set for the current options by overriding this `DataSource` method: + +```rust +fn capabilities(&self) -> Capabilities { + if self.read_only { + // The SDK also drops the truncations, which require their writes. + Capabilities::all().without(Capabilities::BATCH_WRITE | Capabilities::STREAMING_WRITE) + } else { + Capabilities::all() + } +} +``` + +The SDK evaluates this once during `create` and keeps only implemented operations, +so a source can narrow its capabilities but never enable one that it does not +implement, and keeps each truncation only with its write. +An empty set permits schema discovery and close, but rejects operation creation +before calling the connector. The declaration stays fixed for that instance. +The default declaration is `Capabilities::all()`, every operation of the SDK. Limit and +column pruning remain per-scan contracts. + +Spark also calls `create` and `close` during query analysis to discover table +capabilities. A probe uses the table's options, while an operation may override +them with query options and checks capabilities again on a new source instance. +Keep `DataSource::new` and `capabilities` lightweight and safe to drop +immediately; do not assume that `infer_schema` or `new_scan` will follow. Executor +resources belong in `PartitionReaderFactory::open`. + +Spark propagates the native `BATCH_WRITE` and `BATCH_TRUNCATE` flags to +`Table.capabilities()`, as `BATCH_WRITE` and `TRUNCATE`, so a read-only source rejects +batch writes during analysis, before Spark computes their input. Its DSv2 read and +streaming-write flags remain present to avoid V1 fallback; the native flags still reject +unsupported reads or streaming writes during planning. Thus the DSv2 table's flags are not +a literal copy of the native mask declared by the Rust source, and an unsupported +streaming read or write fails when its query starts or plans its first micro-batch, after +`start()` returns. + +## Batch write lifecycle + +```text +Driver: + DataSource::new_write -> BatchWrite + | new_writer_factory() ^ commit(CommitInfo) / abort(AbortInfo) + serialized factory | typed messages + | | +Executor, per task attempt: v | + DataWriterFactory::open(WriterContext) + -> DataWriter::write(RecordBatch)* + -> commit() / abort() -> Drop +``` + +`DataSource::new_write(WriteInfo)` validates the input schema and returns an +independent driver coordinator, a `BatchWrite`. Its `new_writer_factory` returns the +serializable executor configuration of its task writers, which the SDK encodes as the +state of the writer that native `create_writer` returns. Restoring an executor writer +uses only those bytes and the schema that Spark passes with them, without creating a +driver registry. + +Each `DataWriterFactory::open` receives a `WriterContext` with the input schema, partition ID, +and task, and returns a task-bound writer. `write` takes ownership of a +`RecordBatch`, so its Arrow buffers can be retained after the callback, until the writer +is dropped: they belong to the data writer of Spark, and the ABI requires the library to +release them before Spark closes the writer. Spark cannot free a batch that is still +retained when it closes the writer: it logs an error, and the memory stays allocated until +the batch is dropped. The SDK +moves the incoming Arrow array, which has the schema that the data writer got, and +releases imported resources on failures. Input slices need not have zero offsets; +the zero-offset restriction applies to arrays exported to Spark by readers. When Spark +writes the batches of a native scan without converting them to rows, it copies their +values as the scan returned them, without the checks of a conversion, such as the +precision of a decimal. The SDK does validate the layout and values of each incoming batch, +since the safe Arrow accessors rely on them, so a write fails on a string that is not UTF-8, +such as one cast from binary, which a JVM sink writes through as it is. It leaves nullability +to Spark, which accepts nulls under a null parent, even for an element that is not nullable. +Check cancellation during +lengthy writes and use I/O timeouts. + +Task `commit()` returns a typed, serde-serializable message, the `Message` of the +`BatchWrite`. Driver `commit` receives a `CommitInfo` with one winning message per partition, +at the position of its partition; driver `abort` receives an `AbortInfo` whose messages are +`Option<Message>`, with `None` for a partition whose message did not arrive or cannot be +decoded, so a corrupted message cannot prevent cleanup. A failed task or driver commit leaves +the same object available for abort. +A task commit whose message cannot be serialized counts as failed, so `abort` can +follow a `commit` that returned a message. Spark calls each method at most once, never +writes after a failure or a commit, and never aborts a successful commit, as the header +documents; the `# Lifecycle` sections of `BatchWrite` and `DataWriter` list the exact +call-order guarantees. Drop only releases resources. The SDK drops a driver coordinator when +Spark closes its writer, which Spark does right after a successful `commit` or after `abort`, +so the write of a micro-batch is dropped before Spark creates that of the next one. A write +that Spark neither commits nor aborts, and a `ScanBuilder` that Spark never plans, are dropped +when Spark closes their handles, which may be late and on another thread. + +The callback order does not determine the outcome of a remote transaction. A destination +can publish a write successfully but lose its acknowledgement, so `commit` returns an error +and Spark calls `abort`. Connectors must track that outcome with a durable operation identity +and make commit and cleanup idempotent. After an uncertain driver commit, `abort` and Drop +must preserve data that the destination may have published. Use the operation identity to +resolve the outcome before deleting that data; if it remains unknown, leave the data for +later recovery. For streaming, +record the query ID and epoch ID atomically with publication, so a restarted query can +recognize a committed epoch even if the earlier write did not receive its acknowledgement. +The file sink avoids this ambiguity during normal execution by doing no fallible work after +its manifest rename; a remote sink needs its own outcome checks and recovery protocol. + +Stage data per task attempt and publish it only at driver commit. In particular, +`WriteMode::Truncate` must leave existing data intact until that commit. Retries +and speculative attempts may stage data for the same partition; publish only the +attempts whose messages Spark passes to commit. Executor loss can prevent cleanup, +including after task commit, so connectors need a strategy for orphaned data. +Spark provides no batch query ID: generate and serialize an operation identity +when needed. Task-attempt IDs alone are not globally unique across applications. + +When `new_writer_factory` or the serialization of its factory fails, `create_writer` fails, +and when Spark cannot copy the serialized factory, for example when it is too large, Spark +fails the write. Either way, the SDK drops the coordinator without commit or abort, so +Drop must also release what only that write staged. Spark also creates writers late, after +prerequisite AQE shuffle stages, but input computation can still fail during write tasks. +Constructors must therefore avoid irreversible changes. The epoch ID tells the task writers +of batch writes, whose epoch ID is `-1`, from those of micro-batches. + +The [file sink][sink] demonstrates append/truncate using staged JSONL files and +atomic publication of a manifest on a local or shared filesystem. It is a demonstration of +the write lifecycle, not a production template. Its documented +single-writer assumption and orphan cleanup limitations are example constraints, +not transaction guarantees provided by the SDK. + +## Streaming reads and writes + +Micro-batch streaming reads reuse the executor side of batch scans: + +```text +Driver, for each run of a query: + DataSource::new_micro_batch_stream -> MicroBatchStream + initial_offset(), default_read_limit() + latest_offset(LatestOffsetInfo) -> Offset, stored as JSON in the checkpoint + plan(MicroBatchInfo) -> ScanPlan { factory, partitions }, for each micro-batch + commit(CommitOffsetInfo) +Executor, per task: + restored factory + partition + ReaderContext -> Arrow reader -> Arrow C Stream +``` + +Spark creates a stream when a query starts or restarts from its checkpoint, and closes it +when the query stops. It keeps the initial offset in the checkpoint, and asks for it only +when the checkpoint does not have it yet. For each micro-batch, it asks for the latest +offset and plans the data between the previous and latest progress boundaries. +The executors read the partitions of a micro-batch exactly as those of a batch scan: the +two share `read`, which gets the kind of the read. `MicroBatchStreamInfo::schema` has the +columns to read, which are all the columns of the schema until Spark prunes the columns of +streaming scans. Review Comment: Done in 40fbaf065d48: Applied the suggestion: by default the stream gets all the columns, or only the top-level columns the query needs when `spark.sql.streaming.v2ColumnPruning.enabled` is true. -- 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]
