gengliangwang commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4516814931
########## sql/native/rust/tests/streaming.rs: ########## @@ -0,0 +1,889 @@ +// 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, CStr, CString}; +use std::mem::size_of; +use std::ptr; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use arrow_array::ffi::FFI_ArrowArray; +use arrow_array::ffi_stream::{ArrowArrayStreamReader, FFI_ArrowArrayStream}; +use arrow_array::{Array, Int64Array, RecordBatch, StructArray}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_native_source::__private::abi::{ + self, ArrowSchema, SparkDsCommitOffsetInfo, SparkDsCreateInfo, SparkDsDataWriterInfo, + SparkDsFinishDataWriterInfo, SparkDsFinishWriteInfo, SparkDsHost, SparkDsInitialOffsetInfo, + SparkDsLatestOffsetInfo, SparkDsLibrary, SparkDsPartitionsInfo, SparkDsReadInfo, + SparkDsReadLimit, SparkDsReaderInfo, SparkDsStreamPartitionsInfo, SparkDsStreamReaderInfo, + SparkDsTaskContext, SparkDsWriteInfo, ABI_VERSION, +}; +use spark_native_source::{ + Capabilities, CreateInfo, DataSource, DataWriter, DataWriterFactory, LatestOffsetInfo, + MicroBatchStream, MicroBatchStreamInfo, PartitionReader, PartitionReaderFactory, + PartitionWriter, ReadLimit, ReaderContext, Result, ScanBuilder, ScanInfo, ScanPlan, + StreamingWrite, StreamingWriteInfo, Unsupported, WriterContext, +}; + +// Each test exercises the actual exported table; this lock isolates fixture observations. +static TEST_LOCK: Mutex<()> = Mutex::new(()); +static EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new()); +// The position of the latest data of the streams. +static LATEST: AtomicU64 = AtomicU64::new(0); + +#[derive(Clone, Debug, PartialEq)] +enum Event { + StreamCreated(String), + LatestOffset(u64, ReadLimit, Option<u64>), + OffsetCommitted(u64), + WriteCreated { query_id: String, truncate: bool }, + EpochCommitted(i64, Vec<Message>), + EpochAborted(i64, Vec<Option<Message>>), + WriteDropped, +} + +fn record(event: Event) { + EVENTS.lock().unwrap().push(event); +} + +fn events() -> Vec<Event> { + EVENTS.lock().unwrap().clone() +} + +fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])) +} + +fn batch(values: Vec<i64>) -> RecordBatch { + RecordBatch::try_new(schema(), vec![Arc::new(Int64Array::from(values))]).unwrap() +} + +/// Batch and micro-batch reads, whose reader factories have different types, and streaming +/// writes without batch writes. +struct Source { + failure: String, + capabilities: String, + max_rows: Option<u64>, +} + +impl DataSource for Source { + type ScanBuilder = Scan; + type MicroBatchStream = Stream; + type BatchWrite = Unsupported; + type StreamingWrite = Write; + + fn new(info: CreateInfo) -> Result<Self> { + let option = |name: &str| info.options.get(name).cloned().unwrap_or_default(); + Ok(Self { + failure: option("failure"), + capabilities: option("capabilities"), + max_rows: info + .options + .get("maxrows") + .map(|rows| rows.parse()) + .transpose()?, + }) + } + + fn schema(&self) -> Result<SchemaRef> { + Ok(schema()) + } + + fn capabilities(&self) -> Capabilities { + match self.capabilities.as_str() { + "no_streaming_write" => Capabilities::all().without(Capabilities::STREAMING_WRITE), + "append_only" => Capabilities::all().without(Capabilities::STREAMING_TRUNCATE), + _ => Capabilities::all(), + } + } + + fn new_scan(&self, _: ScanInfo) -> Result<Scan> { + Ok(Scan) + } + + fn new_micro_batch_stream(&self, info: MicroBatchStreamInfo) -> Result<Stream> { + if info.schema != schema() { + return Err("unsupported stream schema".into()); + } + record(Event::StreamCreated(info.checkpoint_location)); + Ok(Stream { + failure: self.failure.clone(), + max_rows: self.max_rows, + }) + } + + fn new_streaming_write(&self, info: StreamingWriteInfo) -> Result<Write> { + record(Event::WriteCreated { + query_id: info.query_id, + truncate: info.mode == spark_native_source::WriteMode::Truncate, + }); + Ok(Write) + } +} + +struct Scan; + +impl ScanBuilder for Scan { + type Factory = BatchFactory; + + fn plan(self) -> Result<ScanPlan<BatchFactory>> { + Ok(ScanPlan::new(BatchFactory(100), vec![5])) + } +} + +/// Reads `factory + partition` from each partition of a batch scan. +#[derive(Serialize, Deserialize)] +struct BatchFactory(i64); + +impl PartitionReaderFactory for BatchFactory { + type Partition = i64; + + fn open<'task>( + &self, + partition: i64, + _: ReaderContext<'task>, + ) -> Result<PartitionReader<'task>> { + Ok(Box::new(std::iter::once(Ok(batch(vec![ + self.0 + partition, + ]))))) + } +} + +struct Stream { + failure: String, + max_rows: Option<u64>, +} + +/// The note checks that offsets stay on one line, as Spark requires. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +struct Offset { + position: u64, + note: String, +} + +impl Offset { + fn at(position: u64) -> Self { + Self { + position, + note: "two\nlines".into(), + } + } +} + +impl MicroBatchStream for Stream { + type Offset = Offset; + type Factory = StreamFactory; + + fn initial_offset(&mut self) -> Result<Offset> { + Ok(Offset::at(0)) + } + + fn default_read_limit(&self) -> Result<ReadLimit> { + Ok(self + .max_rows + .map_or(ReadLimit::AllAvailable, ReadLimit::MaxRows)) + } + + fn latest_offset(&mut self, info: LatestOffsetInfo<Offset>) -> Result<Offset> { + if self.failure == "latest_panic" { + panic!("finding the latest offset panicked"); + } + let start = info.start.position; + let run_end = info.run_end.map(|end| end.position); + record(Event::LatestOffset(start, info.limit, run_end)); + let mut end = LATEST.load(Ordering::SeqCst); + if let ReadLimit::MaxRows(rows) = info.limit { + end = end.min(start + rows); + } + Ok(Offset::at(run_end.map_or(end, |run_end| end.min(run_end)))) + } + + fn plan(&mut self, start: Offset, end: Offset) -> Result<ScanPlan<StreamFactory>> { + let positions = (start.position..end.position).collect(); + Ok(ScanPlan::new(StreamFactory { scale: 10 }, positions)) + } + + fn commit(&mut self, end: Offset) -> Result<()> { + record(Event::OffsetCommitted(end.position)); + Ok(()) + } +} + +/// Reads `scale * position` from the partition of each position of a micro-batch. +#[derive(Serialize, Deserialize)] +struct StreamFactory { + scale: i64, +} + +impl PartitionReaderFactory for StreamFactory { + type Partition = u64; + + fn open<'task>( + &self, + position: u64, + _: ReaderContext<'task>, + ) -> Result<PartitionReader<'task>> { + let value = self.scale * position as i64; + Ok(Box::new(std::iter::once(Ok(batch(vec![value]))))) + } +} + +struct Write; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Message { + epoch_id: Option<i64>, + values: Vec<i64>, +} + +impl StreamingWrite for Write { + type Factory = WriteFactory; + type Message = Message; + + const SUPPORTS_TRUNCATE: bool = true; + + fn writer_factory(&self) -> Result<WriteFactory> { + Ok(WriteFactory) + } + + fn commit(&mut self, epoch_id: i64, messages: Vec<Message>) -> Result<()> { + record(Event::EpochCommitted(epoch_id, messages)); + Ok(()) + } + + fn abort(&mut self, epoch_id: i64, messages: Vec<Option<Message>>) -> Result<()> { + record(Event::EpochAborted(epoch_id, messages)); + Ok(()) + } +} + +impl Drop for Write { + fn drop(&mut self) { + record(Event::WriteDropped); + } +} + +#[derive(Serialize, Deserialize)] +struct WriteFactory; + +impl DataWriterFactory for WriteFactory { + type Message = Message; + + fn open<'task>( + &self, + context: WriterContext<'task>, + ) -> Result<PartitionWriter<'task, Message>> { + Ok(Box::new(Writer { + message: Message { + epoch_id: context.epoch_id, + values: vec![], + }, + })) + } +} + +struct Writer { + message: Message, +} + +impl DataWriter for Writer { + type Message = Message; + + fn write(&mut self, batch: RecordBatch) -> Result<()> { + let values = batch + .column(0) + .as_any() + .downcast_ref::<Int64Array>() + .unwrap(); + self.message.values.extend(values.values()); + Ok(()) + } + + fn commit(&mut self) -> Result<Message> { + Ok(self.message.clone()) + } + + fn abort(&mut self) -> Result<()> { + Ok(()) + } +} + +spark_native_source::export_data_source!(Source); + +extern "C" { + fn spark_ds_init(host: *const SparkDsHost, library: *mut *const SparkDsLibrary) -> c_int; +} + +fn library() -> &'static SparkDsLibrary { + // Spark's host structure stays valid until the JVM exits. + let host = Box::leak(Box::new(SparkDsHost { + size: size_of::<SparkDsHost>() as i64, + abi_version: ABI_VERSION, + spark_version: c"test".as_ptr(), + log: None, + is_log_enabled: None, + })); + let mut table = ptr::null(); + assert_eq!(unsafe { spark_ds_init(host, &mut table) }, 0); + unsafe { &*table } +} + +fn error(library: &SparkDsLibrary) -> String { + let message = unsafe { library.last_error.unwrap()() }; + assert!(!message.is_null()); + unsafe { CStr::from_ptr(message) }.to_str().unwrap().into() +} + +fn success(library: &SparkDsLibrary, status: c_int) { + assert_eq!(status, 0, "{}", error(library)); +} + +/// The values that a call passes to its sinks: each sink gets a list of its own. +#[derive(Default)] +struct Sinks { + values: Vec<Vec<u8>>, + states: Vec<Vec<u8>>, +} + +unsafe extern "C" fn add_value(sink: *mut c_void, bytes: *const u8, length: i64) { + let sinks = unsafe { &mut *sink.cast::<Sinks>() }; + sinks + .values + .push(unsafe { std::slice::from_raw_parts(bytes, length as usize) }.to_vec()); +} + +unsafe extern "C" fn set_state(sink: *mut c_void, bytes: *const u8, length: i64) { + let sinks = unsafe { &mut *sink.cast::<Sinks>() }; + sinks + .states + .push(unsafe { std::slice::from_raw_parts(bytes, length as usize) }.to_vec()); +} + +/// Calls a function of the table that passes its results to sinks. +fn emitted(library: &SparkDsLibrary, call: impl FnOnce(*mut c_void) -> c_int) -> (c_int, Sinks) { + let mut sinks = Sinks::default(); + let status = call((&mut sinks as *mut Sinks).cast()); + if status != 0 { + assert!(sinks.values.is_empty() && sinks.states.is_empty()); + let _ = error(library); + } + (status, sinks) +} + +/// The single value of a call, such as an offset. +fn single(library: &SparkDsLibrary, call: impl FnOnce(*mut c_void) -> c_int) -> Vec<u8> { + let (status, mut sinks) = emitted(library, call); + success(library, status); + assert_eq!(sinks.values.len(), 1); + assert!(sinks.states.is_empty()); + sinks.values.pop().unwrap() +} + +/// The partitions of a plan, and its state, which a planning call returns once. +fn planned(library: &SparkDsLibrary, call: impl FnOnce(*mut c_void) -> c_int) -> Sinks { + let (status, sinks) = emitted(library, call); + success(library, status); + assert_eq!(sinks.states.len(), 1, "a plan has a single state"); + sinks +} + +fn source(library: &SparkDsLibrary, options: &[(&str, &str)]) -> (*mut c_void, u64) { + let options: Vec<(CString, CString)> = options + .iter() + .map(|(key, value)| (CString::new(*key).unwrap(), CString::new(*value).unwrap())) + .collect(); + let keys: Vec<*const c_char> = options.iter().map(|(key, _)| key.as_ptr()).collect(); + let values: Vec<*const c_char> = options.iter().map(|(_, value)| value.as_ptr()).collect(); + let info = SparkDsCreateInfo { + size: size_of::<SparkDsCreateInfo>() as i64, + name: c"streaming_test".as_ptr(), + option_keys: keys.as_ptr(), + option_values: values.as_ptr(), + num_options: keys.len() as i64, + }; + let mut mask = 0; + let mut pointer = ptr::null_mut(); + success(library, unsafe { + library.create.unwrap()(&info, &mut mask, &mut pointer) + }); + (pointer, mask) +} + +fn stream_reader(library: &SparkDsLibrary, options: &[(&str, &str)]) -> *mut c_void { + let (source, _) = source(library, options); + let mut schema = ArrowSchema::try_from(schema().as_ref()).unwrap(); + let info = SparkDsStreamReaderInfo { + size: size_of::<SparkDsStreamReaderInfo>() as i64, + checkpoint_location: c"file:/tmp/checkpoint/sources/0".as_ptr(), + }; + let mut reader = ptr::null_mut(); + let status = + unsafe { library.create_stream_reader.unwrap()(source, &mut schema, &info, &mut reader) }; + // Before close, which clears the error of the thread. + success(library, status); + // A stream reader outlives its source, which Spark closes right after creating it. + unsafe { library.close.unwrap()(source) }; + reader +} + +fn read_limit(kind: i32, max_rows: i64) -> SparkDsReadLimit { + SparkDsReadLimit { + size: size_of::<SparkDsReadLimit>() as i64, + kind, + max_rows, + } +} + +fn latest( + library: &SparkDsLibrary, + reader: *mut c_void, + start: &CStr, + limit: &SparkDsReadLimit, + run_end: Option<&CStr>, +) -> (c_int, Sinks) { + let info = SparkDsLatestOffsetInfo { + size: size_of::<SparkDsLatestOffsetInfo>() as i64, + start: start.as_ptr(), + limit, + run_end: run_end.map_or(ptr::null(), CStr::as_ptr), + }; + emitted(library, |sink| unsafe { + library.latest_offset.unwrap()(reader, &info, Some(add_value), sink) + }) +} + +fn stream_partitions( + library: &SparkDsLibrary, + reader: *mut c_void, + start: &CStr, + end: &CStr, +) -> (c_int, Sinks) { + let info = SparkDsStreamPartitionsInfo { + size: size_of::<SparkDsStreamPartitionsInfo>() as i64, + start: start.as_ptr(), + end: end.as_ptr(), + }; + emitted(library, |sink| unsafe { + library.stream_partitions.unwrap()(reader, &info, Some(add_value), Some(set_state), sink) + }) +} + +fn task(partition: i32) -> SparkDsTaskContext { + SparkDsTaskContext { + size: size_of::<SparkDsTaskContext>() as i64, + stage_id: 1, + stage_attempt_number: 0, + partition_id: partition, + attempt_number: 0, + task_attempt_id: 10 + i64::from(partition), + is_interrupted: None, + } +} + +/// Reads a partition with the read function that batch scans and micro-batches share. +fn read(library: &SparkDsLibrary, kind: i32, state: &[u8], partition: &[u8]) -> Vec<i64> { + let task = task(0); + let mut read_schema = ArrowSchema::try_from(schema().as_ref()).unwrap(); + let info = SparkDsReadInfo { + size: size_of::<SparkDsReadInfo>() as i64, + kind, + schema: &mut read_schema, + reader_state: state.as_ptr(), + reader_state_length: state.len() as i64, + partition: partition.as_ptr(), + partition_length: partition.len() as i64, + }; + let mut stream = FFI_ArrowArrayStream::empty(); + success(library, unsafe { + library.read.unwrap()(&task, &info, &mut stream) + }); + ArrowArrayStreamReader::try_new(stream) + .unwrap() + .flat_map(|batch| { + let batch = batch.unwrap(); + let values = batch + .column(0) + .as_any() + .downcast_ref::<Int64Array>() + .unwrap(); + values.values().to_vec() + }) + .collect() +} + +#[test] +fn streaming_operations_declare_their_capabilities_and_callbacks() { + let _guard = TEST_LOCK.lock().unwrap(); Review Comment: Done in e6dfbb81b67c: Every `TEST_LOCK.lock()` in streaming.rs and batch_write.rs now uses `unwrap_or_else(PoisonError::into_inner)`, so one failing test no longer turns every later test into a PoisonError. ########## sql/native/rust/Cargo.toml: ########## @@ -0,0 +1,56 @@ +# 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. + +[package] +name = "spark-native-source" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +description = "Experimental Rust SDK for native data sources of Apache Spark" + +[workspace] +members = [ + "../../../examples/src/main/rust/native-data-source", + "../../../examples/src/main/rust/native-data-sink", +] +default-members = ["."] +resolver = "2" + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +publish = false + +[workspace.dependencies] +arrow-array = { version = "58", features = ["ffi"] } +arrow-schema = { version = "58", features = ["ffi", "serde"] } Review Comment: Done in e6dfbb81b67c: Dropped the `serde` feature of arrow-schema and removed its serde/serde_core edges from Cargo.lock; no serialized type of the SDK or examples contains an Arrow type. -- 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]
