dongjoon-hyun commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4515939437
########## examples/src/main/rust/native-data-source/smoke.py: ########## @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +# 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. + +"""Run with Java 22+ and spark-submit from a distribution with native data sources (4.4.0+).""" + +import argparse +from pathlib import Path Review Comment: **[2] The same isort failure as item 1.** `from pathlib import Path` at L20 has to come after `import tempfile`, and ruff's default `combine-as-imports = false` splits L24 into `from pyspark.sql import SparkSession` and `from pyspark.sql import functions as F`. Could you fix both? ########## examples/src/main/rust/native-data-sink/smoke.py: ########## @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# 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. + +"""Run with Java 22+ and local spark-submit from a build with native data sources (4.4.0+).""" + +import argparse +import json +from pathlib import Path Review Comment: **[3] The same isort failure as item 1.** `from pathlib import Path` at L21 has to come after `import tempfile`, so the job stays red even after items 1 and 2 are fixed. Could you move it too? ########## sql/native/rust/src/write.rs: ########## @@ -0,0 +1,290 @@ +// 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 write coordination and task-local writers restored from serialized state, for batch +//! writes and for the writes of micro-batches. + +use std::ffi::c_void; + +use arrow_array::{ffi, Array, RecordBatch, StructArray}; +use arrow_schema::{DataType, SchemaRef}; +use serde::Serialize; + +use crate::abi::{self, ArrowArray, SparkDsTaskContext}; +use crate::bridge::stream::validate_schema; +use crate::bridge::{decode, describe, drop_provider, encode, provider_call}; +use crate::{ + BatchWrite, DataWriter, DataWriterFactory, PartitionWriter, Result, StreamingWrite, + TaskContext, WriterContext, +}; + +/// A batch write, which a driver writer drives as a streaming write whose epoch ID is always +/// -1 and is ignored. +pub struct Batch<W>(pub W); + +impl<W: BatchWrite> StreamingWrite for Batch<W> { + type Factory = W::Factory; + type Message = W::Message; + + fn writer_factory(&self) -> Result<W::Factory> { + self.0.writer_factory() + } + + fn commit(&mut self, _: i64, messages: Vec<W::Message>) -> Result<()> { + self.0.commit(messages) + } + + fn abort(&mut self, _: i64, messages: Vec<Option<W::Message>>) -> Result<()> { + self.0.abort(messages) + } +} + +/// A driver writer that decodes its own commit messages, so that one handle type holds the +/// driver writers of batch writes and of the writes of micro-batches, which share the writer +/// handles of the ABI. +pub trait DriverWrite: Send { + fn commit(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()>; + + fn abort(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()>; +} + +/// The driver keeps this coordinator until a successful commit or an abort, after which Spark Review Comment: **[4] Following up on @spark-test's [P2](https://github.com/apache/spark/pull/59520#discussion_r4506865939): the root cause is on the JVM side, so libraries that do not use this SDK still hit it.** `NativeDataSourceWriter.commit` and `abort` close the handle (NativeDataSource.scala:536-551), but `NativeDataSourceStreamWriter.commit` and `abort` (L580-590) do not. The handle then stays open until `NativeStreamWriters.register` closes it, after `streamWriter` has already called `create_writer` for the next micro-batch (L156-168, L1409-1414). A C or C++ library, or Rust code written directly against `spark_datasource.h`, that releases an exclusive resource in `close_writer`, like the `.write-lock` of the sink example, fails or blocks at its second micro-batch. NativeDataSource.scala is outside this diff, so I left this here. Minor: could the stream writer close its handle after a successful commit and in a `finally` of abort, as the batch writer does, in a follow-up? `NativeStreamWri ters` would then only close writers that never finish, the lifecycle text of spark_datasource.h:121-124 would change with it, and `DriverWriter` would no longer need to drop the coordinator early. ########## 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: **[6] Minor: one failing test makes every later test of the binary fail with `PoisonError`.** An assertion that fails while it holds `TEST_LOCK` poisons the mutex, so each later `TEST_LOCK.lock().unwrap()` panics and hides which behavior regressed. batch_write.rs:531 and the tests after it do the same. Could they use `TEST_LOCK.lock().unwrap_or_else(PoisonError::into_inner)`, as `lock` in bridge.rs:363 does? ########## examples/src/main/rust/native-data-source/package.py: ########## @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# 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 a compiled connector for the native data source C ABI of Spark.""" + +import argparse +import json +from pathlib import Path Review Comment: **[1] The `Python linter` step of the `Run / Linters, licenses, and dependencies` job fails on fdf0cb1 and ce11eff, and I think these imports are the cause.** `dev/lint-python` runs `ruff check` on the whole tree, `examples/src/main/rust` is not in the `exclude` list of `pyproject.toml`, and its `extend-select` enables isort (`I`). With ruff's default `force-sort-within-sections = false`, every `import x` of a section comes before its `from x import y`, as in the existing Spark files, so `from pathlib import Path` at L21 has to move after `import zipfile` (I001). The PR description says the Python checks passed, but I don't think they included ruff. Could you move it and check the new files with `./dev/lint-python --ruff`? ########## 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: **[7] Nit: the `serde` feature of arrow-schema looks unused now.** It was needed while bridge.rs serialized `ReaderState { factory, schema: Schema }`, but 576c77b removed the schema from the state, and no type of the SDK or of the two examples serializes an Arrow type anymore. The feature still builds serde impls of the Arrow schema types into every connector, and through the `arrow_schema` re-export it gives connectors serde on `Schema` and `DataType` as a side effect. Could `"serde"` be dropped from L40? ########## examples/src/main/rust/native-data-source/tests/c_abi_smoke.rs: ########## @@ -0,0 +1,88 @@ +// 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. + +#![cfg(any(target_os = "linux", target_os = "macos"))] + +use std::error::Error; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{SystemTime, UNIX_EPOCH}; + +struct TestDirectory(PathBuf); + +impl Drop for TestDirectory { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +#[test] +fn c_abi_arrow_round_trip() -> Result<(), Box<dyn Error>> { + let unique = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(); + let directory = TestDirectory( + std::env::temp_dir().join(format!("spark-native-c-{}-{unique}", std::process::id())), + ); + fs::create_dir(&directory.0)?; + + let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); + // The header of the Spark source tree, as a library would copy it. + let header = + manifest.join("../../../../../sql/core/src/main/resources/org/apache/spark/sql/datasource"); + let harness = directory.0.join("c_abi_smoke"); + let compiler = std::env::var_os("CC").unwrap_or_else(|| "cc".into()); Review Comment: **[5] Minor: `CC` is run as one program name.** cc-rs and make accept a `CC` with a launcher or flags, such as `CC="ccache cc"` or `CC="clang -m64"`, but `Command::new` at L46 then looks for a program literally named `ccache cc`. So `cargo test --workspace` fails `c_abi_arrow_round_trip` with "No such file or directory", for a reason unrelated to the ABI. Could the harness split `CC` on whitespace, and pass the remaining words as leading arguments? -- 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]
