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


##########
sql/native/rust/src/stream.rs:
##########
@@ -0,0 +1,844 @@
+// 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(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_nulls(column, field, field.name(), None)?;
+        }
+        Ok(Some(data))
+    }
+}
+
+/// 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(),
+    }
+}
+
+/// 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.
+}
+
+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_nulls.
+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.
+/// `referenced` tells which values belong to a parent value that is not null.
+fn check_nulls(
+    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());
+    }
+    let valid = |index: usize| data.is_valid(index) && is_referenced(index);
+    match field.data_type() {
+        DataType::Struct(fields) => {
+            let mask: Vec<bool> = (0..data.len()).map(valid).collect();

Review Comment:
   Done in 40fbaf065d48: `check_values` now builds a container's mask only for 
the children that `has_checks` selects: a non-nullable field, element, key or 
value that has nulls (from cached null counts), a decimal, or a child with such 
values under it. So a `map<string, string>` without null keys, or a `struct<a 
int not null>` without nulls, builds no mask, and the results and messages stay 
the same.



##########
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,

Review Comment:
   Done in 40fbaf065d48: Added `writes_truncate_only_when_they_declare_it` to 
bridge.rs. Its source's batch and streaming writes keep the default 
`SUPPORTS_TRUNCATE` and its `capabilities()` returns every capability. The test 
expects the mask `BATCH_WRITE | STREAMING_WRITE`, and expects both truncating 
`create_writer` calls to fail with the unsupported-mode error.



##########
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
+limit by shortening the range before splitting it into partitions. The readers 
return the
+columns of the schema to read, in its order, including zero-column batches for 
operations such
+as `COUNT(*)`.
+
+## Planning and reading
+
+`RangeSource::new_scan` creates a driver-side `RangeScan`. Pushdown methods 
update that builder,
+and `plan(self)` consumes it to produce a `ScanPlan<RangeReaderFactory>`. The 
plan contains:
+
+- a serializable `RangeReaderFactory` with the batch size;
+- disjoint `RangePartition` values with inclusive starts and exclusive ends.
+
+Spark passes the schema to read to each reader, so the reader takes its output 
columns, in
+order, from `ReaderContext::schema` instead of carrying them in the factory, 
and the scan does
+not implement `prune_columns`.
+
+This API matches the framework's separation of driver planning and executor 
reading. Spark's
+`NativeBatchPlanner` owns the native handle; its 
`NativePartitionReaderFactory` carries the
+serialized Rust factory and the schema to read to executors. Java 
`ScanBuilder.build()` caches
+a scan but does not call Rust `plan()`. The first request for batch partitions 
or a reader
+factory triggers native `partitions`, which returns the partitions and the 
serialized factory.
+Spark then closes the native driver handle.
+
+The SDK serializes this data for the executors. Each factory opens a lazy 
iterator of Arrow
+batches using a partition and a `ReaderContext`, which carries the schema to 
read and a
+lifetime-bound `TaskContext`. The example checks task cancellation before 
generating each batch
+and keeps memory bounded by the configured batch size. Neither the factory
+nor a partition contains a driver handle or open connection. A storage 
connector can also put a
+snapshot identifier in its factory to make retried reads refer to the same 
data.
+
+A streaming read creates a `RangeStream`, whose offsets are the next row to 
read, such as
+`{"next":13}`. The range is fixed, so all its rows are available when the 
query starts: the
+initial offset is the start of the range, the latest offset its end, and the 
first micro-batch
+reads every row. Later micro-batches find no new data. With 
`maxRowsPerTrigger`,
+`default_read_limit` returns `ReadLimit::MaxRows`, and `latest_offset` ends 
each micro-batch
+after at most that many rows, and not beyond the end of the run of 
`Trigger.AvailableNow`, which
+then reads the range in several micro-batches. `RangeStream::plan` splits the 
rows between two
+offsets into partitions with the `RangeReaderFactory` of batch scans, so the 
executors read a
+micro-batch exactly as a batch scan. A restarted query may plan its last range 
again, from the
+offsets of its checkpoint.
+
+## Build and test
+
+The example builds only in the Spark source tree, not from the copy in a 
binary distribution:

Review Comment:
   Done in 40fbaf065d48: Both example READMEs now say the example builds only 
in the Spark source tree, which binary distributions do not include.



##########
sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h:
##########
@@ -65,7 +65,7 @@
  *   the columns to read and the location of the checkpoint of the source, and 
keeps it until the
  *   streaming query stops. When the checkpoint does not have the initial 
offset of the source yet,
  *   Spark asks for it with initial_offset, and keeps it in the checkpoint. 
For each micro-batch, it
- *   asks for the latest_offset, with the offset that the micro-batch starts 
after, plans the
+ *   asks for the latest_offset, with the starting progress boundary of the 
micro-batch, plans the

Review Comment:
   Done in 40fbaf065d48: Brought the header's wording to the guide: 
`latest_offset` now gets the starting progress boundary, and the guide states 
that equal boundaries describe no data and adjacent ranges must neither repeat 
nor skip records. Updated `ColumnarMicroBatchStream`, 
`ColumnarStreamReader.latestOffset`/`partitions`/`commit`, and 
`NativeLibrary.latestOffset` to match.



##########
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();

Review Comment:
   Done in 40fbaf065d48: Added 
`nested_nulls_are_allowed_under_any_null_ancestor`. For `struct<inner: 
struct<flag NOT NULL>>` and `array<struct<flag NOT NULL>>`, a null flag in a 
valid inner value is accepted under a null outer value. The same null is 
rejected with the message naming `nested.inner.flag` or `values.element.flag` 
when every ancestor is valid.



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