gengliangwang commented on code in PR #59520:
URL: https://github.com/apache/spark/pull/59520#discussion_r4518849570


##########
sql/native/rust/src/lib.rs:
##########
@@ -0,0 +1,760 @@
+// 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.
+
+//! Experimental SDK for native data sources in Rust, over version 1 of the C 
ABI of Spark,
+//! `spark_datasource.h`.
+//!
+//! Implement [`DataSource`], naming the types of the operations that it 
implements: a
+//! [`ScanBuilder`] for batch reads, a [`MicroBatchStream`] for micro-batch 
streaming reads, a
+//! [`BatchWrite`] for batch writes, and a [`StreamingWrite`] for streaming 
writes, or
+//! [`Unsupported`] for an operation that it does not implement. Then invoke
+//! [`export_data_source!`] once in a `cdylib` crate. The SDK
+//! owns handles, plan/message serialization, C ABI adaptation, and Arrow 
import/export.
+//! Rust traits stay inside the plugin; they are not an ABI between dynamic 
libraries.
+//!
+//! Methods receive their inputs in `#[non_exhaustive]` structs, so that new 
ABI fields
+//! can reach connectors without breaking them: `*Info` structs on the driver
+//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], 
[`LatestOffsetInfo`],
+//! [`WriteInfo`], [`StreamingWriteInfo`], and [`HostInfo`]), and `*Context` 
structs, which
+//! carry the live [`TaskContext`], on the executors ([`ReaderContext`] and 
[`WriterContext`]).
+
+use std::collections::BTreeMap;
+
+use arrow_array::RecordBatch;
+use arrow_schema::{ArrowError, SchemaRef};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+
+mod abi;
+mod bridge;
+mod capabilities;
+mod export;
+mod host;
+mod task;
+mod unsupported;
+mod write;
+
+/// Implementation details of [`export_data_source!`] and of the SDK's own 
tests, not an API.
+#[doc(hidden)]
+pub mod __private {
+    pub use crate::bridge::Bridge;
+    pub use crate::export::{library, Exported};
+
+    pub mod abi {
+        pub use crate::abi::*;
+    }
+}
+
+pub use capabilities::Capabilities;
+pub use host::HostInfo;
+/// The `log` crate, whose macros write to the log of the Spark driver or 
executor, with
+/// the path of the library, once Spark initializes the library.
+///
+/// Any thread can call them, including in the dependencies of the library. 
Outside
+/// Spark, for example in unit tests, their messages are dropped. The SDK sets 
the level of
+/// the `log` crate to that of the log of Spark, such as `Debug` when Spark 
logs debug
+/// messages, so the library does not set it.
+pub use log;
+pub use task::TaskContext;
+pub use unsupported::Unsupported;
+
+pub type Error = Box<dyn std::error::Error + Send + Sync>;
+pub type Result<T> = std::result::Result<T, Error>;
+pub type Options = BTreeMap<String, String>;
+
+// Data sources: Spark creates a DataSource for each operation, and its 
associated types
+// name the operations that the source implements.
+
+/// What Spark passes to create a data source.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct CreateInfo {
+    /// The name of the data source, as listed in the manifest of its package, 
or in
+    /// lower case for an installed library. A library that implements several 
data
+    /// sources, installed or listed under each of their names, can choose by 
this name.
+    pub name: String,
+    /// The options, with keys in lower case. A capability probe uses the 
options of the
+    /// table; an operation may override them with the options of its query.
+    pub options: Options,
+}
+
+impl CreateInfo {
+    /// The information of a source created outside Spark, for example in a 
test.
+    pub fn new(name: impl Into<String>, options: Options) -> Self {
+        Self {
+            name: name.into(),
+            options,
+        }
+    }
+}
+
+/// Driver-side source configuration, schema discovery, and the operations of 
a source.
+///
+/// The associated types name the operations that the source implements, and
+/// [`Unsupported`] stands for one that it does not implement:
+///
+/// ```rust,ignore
+/// impl DataSource for RangeSource {
+///     type ScanBuilder = RangeScan;
+///     type MicroBatchStream = RangeStream;
+///     type BatchWrite = Unsupported;
+///     type StreamingWrite = Unsupported;
+///     ...
+/// }
+/// ```
+///
+/// The SDK installs native callbacks and reports capabilities only for the 
implemented
+/// operations, and calls the `new_*` method of an operation only for them.
+///
+/// Spark creates a source for each schema inference, scan, stream, and write, 
including
+/// the write of each micro-batch, and may create one only to inspect its 
capabilities,
+/// then drop it. Keep construction lightweight. Scan builders, streams, and 
writes cannot
+/// borrow their source, which Spark drops first.
+pub trait DataSource: Send + Sized + 'static {
+    fn new(info: CreateInfo) -> Result<Self>;
+
+    /// Called once in each JVM when Spark loads the library, before it 
creates any
+    /// source. On failure, Spark does not use the library, and the error is 
logged.
+    fn init(_host: &HostInfo) -> Result<()> {
+        Ok(())
+    }
+
+    // Schema discovery.
+
+    /// Whether [`schema`](Self::schema) infers the schema of the data. When 
false, the
+    /// SDK leaves the native function unset: Spark then requires a 
user-specified
+    /// schema, reports its standard error without one, and never calls 
`schema`.
+    const INFERS_SCHEMA: bool = true;
+
+    /// Returns the schema of the data, when the user does not specify one.
+    fn schema(&self) -> Result<SchemaRef> {
+        Err(
+            "DataSource::schema is not implemented: implement it, or set \
+             DataSource::INFERS_SCHEMA to false to require a user-specified 
schema"
+                .into(),
+        )
+    }
+
+    // Batch reads.
+
+    /// The scan builder of batch reads, which [`new_scan`](Self::new_scan) 
creates, or
+    /// [`Unsupported`].
+    type ScanBuilder: ScanBuilder;
+
+    /// Creates an independent scan of [`ScanInfo::schema`], which the user 
may have
+    /// specified; reject unsupported schemas.
+    fn new_scan(&self, _info: ScanInfo) -> Result<Self::ScanBuilder> {
+        Err(
+            "DataSource::new_scan is not implemented: implement it, or set \
+             DataSource::ScanBuilder to Unsupported"
+                .into(),
+        )
+    }
+
+    // Micro-batch streaming reads.
+
+    /// The stream of micro-batch streaming reads, which
+    /// [`new_micro_batch_stream`](Self::new_micro_batch_stream) creates, or 
[`Unsupported`].
+    type MicroBatchStream: MicroBatchStream;
+
+    /// Creates the stream of a streaming query that reads the columns of
+    /// [`MicroBatchStreamInfo::schema`]; reject unsupported schemas.
+    fn new_micro_batch_stream(
+        &self,
+        _info: MicroBatchStreamInfo,
+    ) -> Result<Self::MicroBatchStream> {
+        Err(
+            "DataSource::new_micro_batch_stream is not implemented: implement 
it, or set \
+             DataSource::MicroBatchStream to Unsupported"
+                .into(),
+        )
+    }
+
+    // Batch writes.
+
+    /// The coordinator of batch writes, which [`new_write`](Self::new_write) 
creates, or
+    /// [`Unsupported`].
+    type BatchWrite: BatchWrite;
+
+    /// Validate the input schema and create an independent write. 
Construction may be
+    /// followed only by Drop, without commit or abort, so it must not make 
irreversible
+    /// changes. The SDK calls this only while the instance's capabilities 
include
+    /// `BATCH_WRITE`, and passes [`WriteMode::Truncate`] only when they 
include
+    /// `BATCH_TRUNCATE`, which the write declares with 
[`BatchWrite::SUPPORTS_TRUNCATE`].
+    fn new_write(&self, _info: WriteInfo) -> Result<Self::BatchWrite> {
+        Err(
+            "DataSource::new_write is not implemented: implement it, or set \
+             DataSource::BatchWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Streaming writes.
+
+    /// The coordinator of the write of each micro-batch of a streaming query, 
which
+    /// [`new_streaming_write`](Self::new_streaming_write) creates, or 
[`Unsupported`].
+    type StreamingWrite: StreamingWrite;
+
+    /// Validate the input schema and create the write of a micro-batch. As 
with
+    /// [`new_write`](Self::new_write), construction may be followed only by 
Drop, so it must
+    /// not make irreversible changes. The SDK calls this only while the 
instance's
+    /// capabilities include `STREAMING_WRITE`, and passes 
[`WriteMode::Truncate`] only when
+    /// they include `STREAMING_TRUNCATE`, which the write declares with
+    /// [`StreamingWrite::SUPPORTS_TRUNCATE`].
+    fn new_streaming_write(&self, _info: StreamingWriteInfo) -> 
Result<Self::StreamingWrite> {
+        Err(
+            "DataSource::new_streaming_write is not implemented: implement it, 
or set \
+             DataSource::StreamingWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Instance restrictions.
+
+    /// Returns the operations of this instance. The SDK keeps only those that 
the source
+    /// implements, so the default, [`Capabilities::all`], keeps them all. 
Override this to
+    /// restrict an instance, for example for a read-only destination. The SDK 
evaluates
+    /// it once when Spark creates the source. An instance without operations 
still
+    /// supports schema discovery.
+    fn capabilities(&self) -> Capabilities {
+        Capabilities::all()
+    }
+}
+
+// Batch reads: a ScanBuilder negotiates pushdown and plans the scan on the 
driver, and a
+// PartitionReaderFactory opens a reader of each partition on the executors.
+
+/// What Spark passes to create a scan.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ScanInfo {
+    /// The schema to read: the schema of the source, or one that the user 
specified.
+    pub schema: SchemaRef,
+}
+
+impl ScanInfo {
+    /// The information of a scan created outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef) -> Self {
+        Self { schema }
+    }
+}
+
+/// Negotiates pushdown on the driver, then plans the scan.
+///
+/// Spark calls [`push_limit`](Self::push_limit) and 
[`prune_columns`](Self::prune_columns),
+/// each at most once and in this order, then [`plan`](Self::plan), and drops 
the builder.
+/// After a call fails, it makes no other call. It drops a builder without 
planning it when it
+/// does not read the scan, for example to only explain a query. Only the 
serialized factory
+/// and partitions reach the executors.
+pub trait ScanBuilder: Send + Sized + 'static {
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Count rows. Spark pushes a limit only when the query does not filter 
the rows, since
+    /// it filters them after reading.
+    fn push_limit(&mut self, _limit: usize) -> Result<LimitSupport> {
+        Ok(LimitSupport::Unsupported)
+    }
+
+    /// Tells the scan the top-level columns that the query needs, in order, 
so that it can
+    /// plan to read only them. There may be none, for example for `SELECT 
count(*)`: the
+    /// batches then only have a number of rows. Readers get these columns in
+    /// [`ReaderContext::schema`] whether or not the scan implements this 
method.
+    fn prune_columns(&mut self, _columns: &[String]) -> Result<()> {
+        Ok(())
+    }
+
+    fn plan(self) -> Result<ScanPlan<Self::Factory>>;

Review Comment:
   Narrowed in 95a55f04d5f: the methods whose header function has an info 
struct with fields take one now, `MicroBatchStream::plan(MicroBatchInfo)` and 
`commit(CommitOffsetInfo)`, `BatchWrite::commit(CommitInfo)` / 
`abort(AbortInfo)`, and `StreamingWrite::commit(StreamingCommitInfo)` / 
`abort(StreamingAbortInfo)`. `ScanBuilder::plan`, 
`MicroBatchStream::initial_offset` and the `commit` / `abort` of `DataWriter` 
map to `SparkDsPartitionsInfo`, `SparkDsInitialOffsetInfo` and 
`SparkDsFinishDataWriterInfo`, which only have their size, so they keep taking 
no struct, and the docs say that a field added there would be a breaking change 
of the SDK, which its 0.x version allows.



##########
sql/native/rust/src/stream.rs:
##########
@@ -0,0 +1,830 @@
+// 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::{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 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 = project(batch?, &self.expected)?;
+        match &self.schema {
+            Some(schema) if batch.schema() != *schema => {
+                return Err("reader returned a batch with a different 
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_nulls(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.
+fn project(batch: RecordBatch, expected: &Schema) -> Result<RecordBatch> {
+    let schema = batch.schema();
+    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(batch);
+    }
+    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(batch.project(&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<'task>(
+    reader: PartitionReader<'task>,
+    expected_schema: &SchemaRef,
+) -> FFI_ArrowArrayStream {
+    let state = Box::new(StreamState {
+        reader: Some(reader),
+        expected: expected_schema.clone(),
+        schema: 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 {
+    let Err(message) = provider_call(|| action(state)) else {
+        return 0;
+    };
+    state.finished = true;
+    state.last_error = Some(c_message(message));
+    5 // EIO; get_last_error supplies the provider's actual error message.
+}

Review Comment:
   Done in 2694d61f030: after a callback fails, later `get_schema` and 
`get_next` calls fail with the same error. The README and the 
`PartitionReaderFactory::open` docs say so, and the tests that asserted the end 
of a failed stream now assert that it stays failed.



-- 
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]

Reply via email to