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


##########
sql/native/rust/src/abi.rs:
##########
@@ -0,0 +1,1015 @@
+// 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.
+
+//! Bindings and adapters for version 1 of `spark_datasource.h`.
+
+use std::cell::RefCell;
+use std::ffi::{c_char, c_int, c_void, CStr, CString};
+use std::mem::{offset_of, size_of, MaybeUninit};
+use std::sync::Arc;
+
+pub use arrow_array::ffi::FFI_ArrowArray as ArrowArray;
+pub use arrow_array::ffi_stream::FFI_ArrowArrayStream as ArrowArrayStream;
+pub use arrow_schema::ffi::FFI_ArrowSchema as ArrowSchema;
+use arrow_schema::{Schema, SchemaRef};
+
+use crate::bridge::{c_message, provider_call};
+use crate::host::{self, LogEnabledFunction, LogFunction};
+use crate::{CreateInfo, HostInfo, LatestOffsetInfo, Options, ReadLimit, 
Result, WriteMode};
+
+pub const ABI_VERSION: i32 = 1;
+pub const BATCH_READ: u64 = 1;
+pub const MICRO_BATCH_READ: u64 = 2;
+pub const BATCH_WRITE: u64 = 4;
+pub const STREAMING_WRITE: u64 = 8;
+pub const BATCH_TRUNCATE: u64 = 16;
+pub const STREAMING_TRUNCATE: u64 = 32;
+pub const ADMISSION_CONTROL: u64 = 64;
+pub const READ_BATCH: i32 = 0;
+pub const READ_MICRO_BATCH: i32 = 1;
+pub const READ_ALL_AVAILABLE: i32 = 0;
+pub const READ_MAX_ROWS: i32 = 1;
+pub const WRITE_APPEND: i32 = 0;
+pub const WRITE_TRUNCATE: i32 = 1;
+pub const LOG_ERROR: i32 = 1;
+
+pub type SparkDsSink = Option<unsafe extern "C" fn(*mut c_void, *const u8, 
i64)>;
+pub type Interrupted = unsafe extern "C" fn(*const SparkDsTaskContext) -> bool;
+
+// What Spark passes to the library.
+
+#[repr(C)]
+pub struct SparkDsHost {
+    pub size: i64,
+    pub abi_version: i32,
+    pub spark_version: *const c_char,
+    pub log: Option<LogFunction>,
+    pub is_log_enabled: Option<LogEnabledFunction>,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsCreateInfo {
+    pub size: i64,
+    pub name: *const c_char,
+    pub option_keys: *const *const c_char,
+    pub option_values: *const *const c_char,
+    pub num_options: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsReaderInfo {
+    pub size: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsPartitionsInfo {
+    pub size: i64,
+}
+
+/// The domain of a column, which `push_domains` gets. The SDK binds it, so 
that the function
+/// table has the size of the header, but does not expose it yet (SPARK-61306).
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsDomain {
+    pub size: i64,
+    pub path: *const i32,
+    pub path_length: i64,
+    pub null_allowed: bool,
+    pub nan_allowed: bool,
+    pub ranges: *mut ArrowArray,
+    pub ranges_schema: *mut ArrowSchema,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsStreamReaderInfo {
+    pub size: i64,
+    pub checkpoint_location: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsInitialOffsetInfo {
+    pub size: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsReadLimit {
+    pub size: i64,
+    pub kind: i32,
+    pub max_rows: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsLatestOffsetInfo {
+    pub size: i64,
+    pub start: *const c_char,
+    pub limit: *const SparkDsReadLimit,
+    pub run_end: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsStreamPartitionsInfo {
+    pub size: i64,
+    pub start: *const c_char,
+    pub end: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsCommitOffsetInfo {
+    pub size: i64,
+    pub end: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsTaskContext {
+    pub size: i64,
+    pub stage_id: i32,
+    pub stage_attempt_number: i32,
+    pub partition_id: i32,
+    pub attempt_number: i32,
+    pub task_attempt_id: i64,
+    pub is_interrupted: Option<Interrupted>,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsReadInfo {
+    pub size: i64,
+    pub kind: i32,
+    pub schema: *mut ArrowSchema,
+    pub reader_state: *const u8,
+    pub reader_state_length: i64,
+    pub partition: *const u8,
+    pub partition_length: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsWriteInfo {
+    pub size: i64,
+    pub mode: i32,
+    pub query_id: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsDataWriterInfo {
+    pub size: i64,
+    pub schema: *mut ArrowSchema,
+    pub writer_state: *const u8,
+    pub writer_state_length: i64,
+    pub epoch_id: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsFinishWriteInfo {
+    pub size: i64,
+    pub epoch_id: i64,
+    pub messages: *const *const u8,
+    pub message_lengths: *const i64,
+    pub num_messages: i64,
+    pub rejected: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsFinishDataWriterInfo {
+    pub size: i64,
+}
+
+// What the library returns to Spark.
+
+/// The complete version 1 table. Unsupported operations have null function 
slots.
+#[repr(C)]
+pub struct SparkDsLibrary {
+    pub size: i64,
+    pub abi_version: i32,
+    pub last_error: Option<unsafe extern "C" fn() -> *const c_char>,
+    pub create:
+        Option<unsafe extern "C" fn(*const SparkDsCreateInfo, *mut u64, *mut 
*mut c_void) -> c_int>,
+    pub schema: Option<unsafe extern "C" fn(*mut c_void, *mut ArrowSchema) -> 
c_int>,
+    pub create_reader: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *mut ArrowSchema,
+            *const SparkDsReaderInfo,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub create_stream_reader: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *mut ArrowSchema,
+            *const SparkDsStreamReaderInfo,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub create_writer: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *mut ArrowSchema,
+            *const SparkDsWriteInfo,
+            SparkDsSink,
+            *mut c_void,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub close: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub push_limit: Option<unsafe extern "C" fn(*mut c_void, i32, *mut bool) 
-> c_int>,
+    pub prune_columns:
+        Option<unsafe extern "C" fn(*mut c_void, *const *const c_char, i64) -> 
c_int>,
+    pub partitions: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsPartitionsInfo,
+            SparkDsSink,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub close_reader: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub initial_offset: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsInitialOffsetInfo,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub latest_offset: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsLatestOffsetInfo,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub stream_partitions: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsStreamPartitionsInfo,
+            SparkDsSink,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub commit_offset:
+        Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsCommitOffsetInfo) -> c_int>,
+    pub close_stream_reader: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub read: Option<
+        unsafe extern "C" fn(
+            *const SparkDsTaskContext,
+            *const SparkDsReadInfo,
+            *mut ArrowArrayStream,
+        ) -> c_int,
+    >,
+    pub commit: Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsFinishWriteInfo) -> c_int>,
+    pub abort: Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsFinishWriteInfo) -> c_int>,
+    pub close_writer: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub create_data_writer: Option<
+        unsafe extern "C" fn(
+            *const SparkDsTaskContext,
+            *const SparkDsDataWriterInfo,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub write: Option<unsafe extern "C" fn(*mut c_void, *mut ArrowArray) -> 
c_int>,
+    pub commit_data_writer: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsFinishDataWriterInfo,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub abort_data_writer:
+        Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsFinishDataWriterInfo) -> c_int>,
+    pub close_data_writer: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub default_read_limit:
+        Option<unsafe extern "C" fn(*mut c_void, *mut SparkDsReadLimit) -> 
c_int>,
+    // Added to version 1 by SPARK-61200, after the other functions.
+    pub push_domains: Option<
+        unsafe extern "C" fn(*mut c_void, *const *const SparkDsDomain, i64, 
*mut bool) -> c_int,
+    >,
+}
+
+// The known sizes and field offsets on 64-bit targets, checked wherever the 
SDK builds.
+// Tests also compare the actual Rust layouts with the current C header, using 
this field list.
+macro_rules! layout {
+    ($($name:ident: $size:literal { $($field:ident: $offset:literal),* $(,)? 
})*) => {
+        #[cfg(target_pointer_width = "64")]
+        const _: () = {
+            $(
+                assert!(size_of::<$name>() == $size);
+                $(assert!(offset_of!($name, $field) == $offset);)*
+            )*
+        };
+
+        #[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
+        fn c_layout_assertions() -> String {
+            use std::fmt::Write;
+
+            let mut source =
+                String::from("#include <stddef.h>\n#include 
\"spark_datasource.h\"\n");
+            $(
+                writeln!(
+                    source,
+                    "_Static_assert(sizeof({0}) == {1}, \"{0}: size\");",
+                    stringify!($name),
+                    size_of::<$name>(),
+                ).unwrap();
+                writeln!(
+                    source,
+                    "_Static_assert(_Alignof({0}) == {1}, \"{0}: 
alignment\");",
+                    stringify!($name),
+                    std::mem::align_of::<$name>(),
+                ).unwrap();
+                $(
+                    writeln!(
+                        source,
+                        "_Static_assert(offsetof({0}, {1}) == {2}, \"{0}.{1}: 
offset\");",
+                        stringify!($name),
+                        stringify!($field),
+                        offset_of!($name, $field),
+                    ).unwrap();
+                )*
+            )*
+            source
+        }
+    };
+}
+
+layout! {
+    SparkDsHost: 40 { size: 0, abi_version: 8, spark_version: 16, log: 24, 
is_log_enabled: 32 }
+    SparkDsCreateInfo: 40 {
+        size: 0, name: 8, option_keys: 16, option_values: 24, num_options: 32,
+    }
+    SparkDsReaderInfo: 8 { size: 0 }
+    SparkDsPartitionsInfo: 8 { size: 0 }
+    SparkDsDomain: 48 {
+        size: 0, path: 8, path_length: 16, null_allowed: 24, nan_allowed: 25, 
ranges: 32,
+        ranges_schema: 40,
+    }
+    SparkDsStreamReaderInfo: 16 { size: 0, checkpoint_location: 8 }
+    SparkDsInitialOffsetInfo: 8 { size: 0 }
+    SparkDsReadLimit: 24 { size: 0, kind: 8, max_rows: 16 }
+    SparkDsLatestOffsetInfo: 32 { size: 0, start: 8, limit: 16, run_end: 24 }
+    SparkDsStreamPartitionsInfo: 24 { size: 0, start: 8, end: 16 }
+    SparkDsCommitOffsetInfo: 16 { size: 0, end: 8 }
+    SparkDsTaskContext: 40 {
+        size: 0, stage_id: 8, stage_attempt_number: 12, partition_id: 16, 
attempt_number: 20,
+        task_attempt_id: 24, is_interrupted: 32,
+    }
+    SparkDsReadInfo: 56 {
+        size: 0, kind: 8, schema: 16, reader_state: 24, reader_state_length: 
32, partition: 40,
+        partition_length: 48,
+    }
+    SparkDsWriteInfo: 24 { size: 0, mode: 8, query_id: 16 }
+    SparkDsDataWriterInfo: 40 {
+        size: 0, schema: 8, writer_state: 16, writer_state_length: 24, 
epoch_id: 32,
+    }
+    SparkDsFinishWriteInfo: 48 {
+        size: 0, epoch_id: 8, messages: 16, message_lengths: 24, num_messages: 
32, rejected: 40,
+    }
+    SparkDsFinishDataWriterInfo: 8 { size: 0 }
+    SparkDsLibrary: 232 {
+        size: 0, abi_version: 8, last_error: 16, create: 24, schema: 32, 
create_reader: 40,
+        create_stream_reader: 48, create_writer: 56, close: 64, push_limit: 72,
+        prune_columns: 80, partitions: 88, close_reader: 96, initial_offset: 
104,
+        latest_offset: 112, stream_partitions: 120, commit_offset: 128,
+        close_stream_reader: 136, read: 144, commit: 152, abort: 160, 
close_writer: 168,
+        create_data_writer: 176, write: 184, commit_data_writer: 192, 
abort_data_writer: 200,
+        close_data_writer: 208, default_read_limit: 216, push_domains: 224,
+    }
+}
+
+/// A structure that Spark passes to the library, to read or to fill.
+///
+/// # Safety
+/// All zero bytes must be a valid value of every field after the first 
`MIN_SIZE` bytes, as they
+/// are for numbers, pointers, and optional functions.
+pub unsafe trait Input: Copy {
+    /// The size of the structure in Spark 4.4.0, the first release of version 
1 of the ABI, which
+    /// is the least that Spark passes. A field that a later release appends 
does not change it:
+    /// [`input`] reads such a field and [`fill`] sets it only when Spark 
passes it.
+    const MIN_SIZE: usize;
+}
+
+// The structures that Spark passes, with their sizes in Spark 4.4.0 on 64-bit 
targets. So far,
+// each binding has the fields of 4.4.0, so its minimum is its size. Once a 
binding has a field
+// that a later release appended, its minimum must be the offset of that field 
instead, as the
+// assertion checks.
+macro_rules! inputs {
+    ($($name:ident: $size:literal),* $(,)?) => {
+        $(
+            // SAFETY: the fields of the bindings are numbers, booleans, 
pointers, and optional
+            // functions.
+            unsafe impl Input for $name {
+                const MIN_SIZE: usize = size_of::<$name>();
+            }
+        )*
+
+        #[cfg(target_pointer_width = "64")]
+        const _: () = {
+            $(assert!(<$name as Input>::MIN_SIZE == $size);)*
+        };
+    };
+}
+
+inputs! {
+    SparkDsCreateInfo: 40,
+    SparkDsReaderInfo: 8,
+    SparkDsPartitionsInfo: 8,
+    SparkDsDomain: 48,
+    SparkDsStreamReaderInfo: 16,
+    SparkDsInitialOffsetInfo: 8,
+    SparkDsReadLimit: 24,
+    SparkDsLatestOffsetInfo: 32,
+    SparkDsStreamPartitionsInfo: 24,
+    SparkDsCommitOffsetInfo: 16,
+    SparkDsTaskContext: 40,
+    SparkDsReadInfo: 56,
+    SparkDsWriteInfo: 24,
+    SparkDsDataWriterInfo: 40,
+    SparkDsFinishWriteInfo: 48,
+    SparkDsFinishDataWriterInfo: 8,
+}
+
+thread_local! {
+    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
+}
+
+/// Converts provider failures and unwinding panics into the C error 
convention.
+pub fn call(action: impl FnOnce() -> Result<()>) -> c_int {
+    LAST_ERROR.with(|error| *error.borrow_mut() = None);
+    let Err(message) = provider_call(action) else {
+        return 0;
+    };
+    LAST_ERROR.with(|error| *error.borrow_mut() = Some(c_message(message)));
+    1
+}
+
+/// Returns the calling thread's error until its next adapter call.
+///
+/// # Safety
+/// The returned pointer must not be freed or used after another adapter call 
on this thread.
+pub unsafe extern "C" fn last_error() -> *const c_char {
+    LAST_ERROR.with(|error| {
+        error
+            .borrow()
+            .as_ref()
+            .map_or(std::ptr::null(), |message| message.as_ptr())
+    })
+}
+
+/// Reads only a field that fits in a sized C structure.
+///
+/// # Safety
+/// `pointer` must address `size` readable bytes, and `offset` must identify a 
field of type `T`.
+pub unsafe fn field<T: Copy>(pointer: *const u8, size: i64, offset: usize) -> 
Option<T> {
+    let end = offset.checked_add(size_of::<T>())?;
+    if usize::try_from(size).ok()? < end {
+        return None;
+    }
+    Some(unsafe { pointer.add(offset).cast::<T>().read_unaligned() })
+}
+
+/// # Safety
+/// A non-null pointer must address the size prefix of a live C structure.
+pub unsafe fn struct_size<T>(pointer: *const T) -> Result<i64> {
+    if pointer.is_null() {
+        return Err("null sized structure".into());
+    }
+    let size = unsafe { pointer.cast::<i64>().read_unaligned() };
+    if size < size_of::<i64>() as i64 {
+        return Err("structure is smaller than its size field".into());
+    }
+    Ok(size)
+}
+
+/// Copies a structure that Spark passes, which has at least the fields of 
Spark 4.4.0: fields are
+/// only appended to the structures, so a shorter one is an error. The fields 
of the binding that
+/// Spark does not pass, because a later release appended them, are zero.
+///
+/// # Safety
+/// A non-null pointer must address a live structure whose first field is its 
size.
+pub unsafe fn input<T: Input>(pointer: *const T) -> Result<T> {
+    let size = unsafe { struct_size(pointer)? };
+    if size < T::MIN_SIZE as i64 {
+        let name = std::any::type_name::<T>()
+            .rsplit("::")
+            .next()
+            .unwrap_or("structure");
+        return Err(
+            format!("{name} has {size} bytes, fewer than in version 1 of the 
native ABI").into(),
+        );
+    }
+    let mut value = MaybeUninit::<T>::zeroed();
+    unsafe {
+        std::ptr::copy_nonoverlapping(
+            pointer.cast::<u8>(),
+            value.as_mut_ptr().cast::<u8>(),
+            fitting::<T>(size),
+        );
+        // The bytes that Spark does not pass are zero, which Input makes 
valid.
+        Ok(value.assume_init())
+    }
+}
+
+/// Sets the fields of a structure that Spark passes for the library to fill, 
such as the
+/// SparkDsReadLimit of default_read_limit, that fit in its size.
+///
+/// # Safety
+/// `pointer` must address a live structure whose first field is its size.
+pub unsafe fn fill<T: Input>(pointer: *mut T, value: &T) -> Result<()> {
+    let size = unsafe { struct_size(pointer.cast_const())? };
+    unsafe {
+        std::ptr::copy_nonoverlapping(
+            (value as *const T).cast::<u8>(),
+            pointer.cast::<u8>(),
+            fitting::<T>(size),
+        )
+    };
+    Ok(())
+}
+
+/// The bytes of a binding that fit in a structure of `size` bytes.
+fn fitting<T>(size: i64) -> usize {
+    usize::try_from(size).map_or(size_of::<T>(), |size| 
size.min(size_of::<T>()))
+}
+
+pub fn require_output<T>(pointer: *mut T) -> Result<()> {
+    if pointer.is_null() {
+        return Err("null output pointer".into());
+    }
+    Ok(())
+}
+
+/// Negotiates the ABI version, installs the host's log, and runs the source's 
`init`.
+///
+/// # Safety
+/// `host` and `output` must follow the `spark_ds_init` contract of the C 
header.
+pub unsafe fn initialize(
+    host: *const SparkDsHost,
+    output: *mut *const SparkDsLibrary,
+    library: &'static SparkDsLibrary,
+    init: fn(&HostInfo) -> Result<()>,
+) -> c_int {
+    let result = call(|| {
+        require_output(output)?;
+        unsafe { output.write(std::ptr::null()) };
+        let size = unsafe { struct_size(host)? };
+        let pointer = host.cast();
+        let version: i32 = unsafe { field(pointer, size, 
offset_of!(SparkDsHost, abi_version)) }
+            .ok_or("host does not provide an ABI version")?;
+        if version < ABI_VERSION {
+            return Err(format!("host ABI {version} does not support ABI 
{ABI_VERSION}").into());
+        }
+        let log: Option<Option<LogFunction>> =
+            unsafe { field(pointer, size, offset_of!(SparkDsHost, log)) };
+        let is_log_enabled: Option<Option<LogEnabledFunction>> =
+            unsafe { field(pointer, size, offset_of!(SparkDsHost, 
is_log_enabled)) };
+        host::install(log.flatten(), is_log_enabled.flatten());
+        let spark_version: Option<*const c_char> =
+            unsafe { field(pointer, size, offset_of!(SparkDsHost, 
spark_version)) };

Review Comment:
   One case is still open: the test runs `initialize` with a host older than 
`ABI_VERSION` (L941) and one equal to it (L954), but not a newer one, which a 
library must accept (spark_datasource.h L225-L227: spark_ds_init gets the 
newest version that Spark supports). So `version != ABI_VERSION` at L587 would 
still pass. Could it also run with `host.abi_version = ABI_VERSION + 1` and 
expect the same "init received Spark 4.4.0"?



##########
sql/native/rust/src/lib.rs:
##########
@@ -0,0 +1,929 @@
+// 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: `*Info` 
structs on the driver
+//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], 
[`LatestOffsetInfo`],
+//! [`MicroBatchInfo`], [`CommitOffsetInfo`], [`WriteInfo`], [`CommitInfo`], 
[`AbortInfo`],
+//! [`StreamingWriteInfo`], [`StreamingCommitInfo`], and 
[`StreamingAbortInfo`]), `*Context`
+//! structs, which carry the live [`TaskContext`], on the executors 
([`ReaderContext`] and
+//! [`WriterContext`]), and [`HostInfo`], which [`DataSource::init`] receives 
in every JVM
+//! that loads the library, executors included. The methods whose function of 
the header
+//! passes nothing but the size of its info struct yet, [`ScanBuilder::plan`],
+//! [`MicroBatchStream::initial_offset`], and the `commit` and `abort` of 
[`DataWriter`], take
+//! no struct: a field added there would be a breaking change of the SDK.
+
+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::*;
+    }
+}
+
+/// The Arrow crate of [`RecordBatch`], which connectors can use to have the 
same version of
+/// Arrow as the SDK.
+pub use arrow_array;
+/// The Arrow crate of [`SchemaRef`] and [`ArrowError`], which connectors can 
use to have the
+/// same version of Arrow as the SDK.
+pub use arrow_schema;
+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.
+///
+/// Use [`Self::new`] to construct this value outside Spark, and include `..` 
when
+/// destructuring it to allow additional fields.
+#[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 [`infer_schema`](Self::infer_schema) infers the schema of the 
data. When
+    /// false, the SDK leaves the native `schema` function unset: Spark then 
requires a
+    /// user-specified schema, reports its standard error without one, and 
never calls
+    /// `infer_schema`.
+    const INFERS_SCHEMA: bool = true;
+
+    /// Returns the schema of the data, when the user does not specify one.
+    fn infer_schema(&self) -> Result<SchemaRef> {
+        Err(
+            "DataSource::infer_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.
+///
+/// Use [`Self::new`] to construct this value outside Spark, and include `..` 
when
+/// destructuring it to allow additional fields.
+#[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, once the scan 
is no longer
+/// referenced, which may be late and on another thread, so a builder must not 
hold a resource
+/// that other operations need exclusively, such as a lock, until Drop. 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;
+
+    /// Pushes a LIMIT of `limit` rows down to the scan. Return 
[`LimitSupport::Global`] only
+    /// if the whole scan then returns at most `limit` 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>>;
+}
+
+/// Whether a connector limits the rows produced by the whole scan.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum LimitSupport {
+    /// The scan may return more rows than the limit. A connector may still 
cap the
+    /// rows of each partition on its own: Spark applies its limit after 
reading.
+    Unsupported,
+    /// The whole scan returns at most the limit. Spark still applies its 
limit.
+    Global,
+}
+
+/// A driver-created plan containing only serializable values.
+///
+/// The SDK serializes the reader factory once and each partition 
independently.
+/// Include snapshot identifiers when needed for repeatable task attempts. Do 
not
+/// put pointers, open files, connections, or process-local resources here.
+#[non_exhaustive]
+pub struct ScanPlan<F: PartitionReaderFactory> {
+    pub factory: F,
+    pub partitions: Vec<F::Partition>,
+}
+
+impl<F: PartitionReaderFactory> ScanPlan<F> {
+    pub fn new(factory: F, partitions: Vec<F::Partition>) -> Self {
+        Self {
+            factory,
+            partitions,
+        }
+    }
+}
+
+/// Serializable configuration from which executors open partition readers.
+///
+/// The factory carries configuration or a snapshot descriptor; open 
connections and
+/// other live resources in [`open`](Self::open). Spark passes the schema to 
read with
+/// each partition, so the factory need not carry it.
+pub trait PartitionReaderFactory: Serialize + DeserializeOwned + Send + 
'static {
+    type Partition: Serialize + DeserializeOwned + Send + 'static;
+
+    /// Opens a lazy reader of the batches of `partition`, with the columns of
+    /// [`ReaderContext::schema`].
+    ///
+    /// - Return batches lazily, with bounded memory.
+    /// - The reader owns its resources and cannot borrow this short-lived 
factory. It
+    ///   may keep `context` until Spark releases the stream.
+    /// - Spark may call the reader on different threads, never concurrently, 
so it must
+    ///   be `Send` but not necessarily `Sync`.
+    /// - Check [`TaskContext::is_interrupted`] during long operations, and 
use timeouts
+    ///   for blocking I/O.
+    /// - Batches must own their buffers, because Spark may release the stream 
before
+    ///   its batches.
+    /// - Spark may open the same partition at the same time in several 
attempts of its
+    ///   task, so a reader must not take a resource that another attempt 
needs exclusively.
+    ///
+    /// The SDK checks Spark-compatible Arrow types, the schema to read and its
+    /// nullability, the precision of decimal values, and zero array offsets 
recursively. It
+    /// reports incompatible layouts instead of copying buffers. After a batch 
fails these
+    /// checks, or the reader returns an error, the stream fails every later 
call with the
+    /// same error. A batch may have more columns than the schema to read,
+    /// such as all the columns of the source: the SDK keeps those of the 
schema, by name.
+    /// Batches may use any supported Arrow encoding of a Spark type, such as 
`LargeUtf8`
+    /// for a string, but the first batch determines the Arrow schema of the 
stream, which
+    /// every later batch must have.
+    fn open<'task>(
+        &self,
+        partition: Self::Partition,
+        context: ReaderContext<'task>,
+    ) -> Result<PartitionReader<'task>>;
+}
+
+/// What an executor reader receives with its partition.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ReaderContext<'task> {
+    /// The schema to read: the columns that the scan reads, in order, which 
are those of
+    /// [`ScanBuilder::prune_columns`] for a batch scan, and of
+    /// [`MicroBatchStreamInfo::schema`] for a micro-batch.
+    pub schema: SchemaRef,
+    /// The index of this partition in the scan or micro-batch's 
[`ScanPlan::partitions`].
+    /// This is not the Spark task's partition ID: one task may read several 
partitions,
+    /// for example after a coalesce or union. The index is unique only within 
that plan.
+    pub partition_index: i32,
+    /// The task that reads the partition.
+    pub task: TaskContext<'task>,
+}
+
+impl<'task> ReaderContext<'task> {
+    /// The context of a reader opened outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef, partition_index: i32, task: 
TaskContext<'task>) -> Self {
+        Self {
+            schema,
+            partition_index,
+            task,
+        }
+    }
+}
+
+/// The lazy batches of one partition, which [`PartitionReaderFactory::open`] 
returns.
+/// Any Arrow `RecordBatchReader`, such as a Parquet reader, is such an 
iterator.
+pub type PartitionReader<'task> =
+    Box<dyn Iterator<Item = std::result::Result<RecordBatch, ArrowError>> + 
Send + 'task>;
+
+// Micro-batch streaming reads: a MicroBatchStream finds new data and plans 
each micro-batch on
+// the driver, and the PartitionReaderFactory of each plan reads its 
partitions on the executors,
+// as in batch reads.
+
+/// What Spark passes to create the stream of a streaming query.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct MicroBatchStreamInfo {
+    /// The columns to read: those of the schema of the source, or of one that 
the user
+    /// specified, or only the top-level columns of it that the query needs. 
The readers of
+    /// the micro-batches get it in [`ReaderContext::schema`].
+    pub schema: SchemaRef,
+    /// A directory in the checkpoint of the query that is reserved for this 
source, such as
+    /// `file:/tmp/checkpoint/sources/0`, where the stream may keep what it 
needs to recover
+    /// from a failure. It stays the same when the query restarts. It is a 
fully qualified
+    /// Hadoop path, whose characters are not escaped as in a URI, on a file 
system that the
+    /// library may not be able to access, such as `s3a`. Spark keeps what it 
needs there under
+    /// the names that start with `_spark`, which the library must not use.
+    pub checkpoint_location: String,
+}
+
+impl MicroBatchStreamInfo {
+    /// The information of a stream created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, checkpoint_location: impl Into<String>) -> 
Self {
+        Self {
+            schema,
+            checkpoint_location: checkpoint_location.into(),
+        }
+    }
+}
+
+/// Finds new data and plans the micro-batches of a streaming query, on the 
driver.
+///
+/// Spark creates a stream when a streaming query starts, or restarts from its 
checkpoint,
+/// and drops it when the query stops. For each micro-batch, it asks for the
+/// [`latest_offset`](Self::latest_offset), and when that differs from the end 
of the
+/// previous micro-batch, [`plan`](Self::plan)s the data in between. Only the 
serialized
+/// factory and partitions of each plan reach the executors, which read them 
as those of a
+/// batch scan.
+///
+/// # Offsets
+///
+/// An offset is a progress boundary whose representation and mapping to 
records the connector
+/// defines. A micro-batch reads the data between its starting and ending 
boundaries. For example,
+/// when an offset stores the next row to read, `{"next":10}` to `{"next":13}` 
reads rows 10, 11,
+/// and 12: the row range is `[10, 13)`. Equal boundaries describe no data, 
and adjacent ranges
+/// must neither repeat nor skip records.
+///
+/// Spark stores offsets in the checkpoint of the query, as the JSON of
+/// [`Offset`](Self::Offset), and compares them by that JSON, so serialize a 
position to the
+/// same JSON each time: for example, use structs and `BTreeMap` rather than 
`HashMap`. The
+/// SDK stores exactly that JSON, and later versions will not wrap or 
re-encode it: the format
+/// of an offset is that of the connector's type, which outlives any build of 
the library. A
+/// restarted query passes the offsets of its checkpoint, which an earlier 
version of the
+/// library may have written, to `latest_offset`, `plan`, and `commit`. When 
that version had a
+/// different `Offset` type, the same position may encode to different JSON, 
so Spark runs one
+/// micro-batch without rows.
+///
+/// # Admission control
+///
+/// [`default_read_limit`](Self::default_read_limit) limits the data of each 
micro-batch,
+/// typically with an option of the source. Spark passes the limit to 
`latest_offset`, except
+/// when a micro-batch reads all the available data, as with `Trigger.Once`. 
With
+/// `Trigger.AvailableNow`, a run reads the data that was available when it 
started: with a
+/// limit, in several micro-batches, whose latest offsets must not go beyond
+/// [`LatestOffsetInfo::run_end`].
+///
+/// # Lifecycle
+///
+/// - Calls never run concurrently.
+/// - After a call fails, including with a panic, Spark makes no other call: 
it stops the
+///   query, and drops the stream.
+/// - After a restart, Spark may plan the last range of the query again, so 
`plan` must
+///   return partitions that read the same data for the same range.
+pub trait MicroBatchStream: Send + 'static {
+    /// A progress boundary in the data, such as the next record of each 
partition of a log.
+    type Offset: Serialize + DeserializeOwned;
+
+    /// The reader factory of the micro-batches, which can be that of batch 
scans.
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Returns the starting progress boundary when the query has no 
checkpoint. Spark keeps
+    /// it in the checkpoint, and asks only when the checkpoint does not have 
it yet, so a query
+    /// that restarts before its first micro-batch is committed starts from 
the same offset.
+    fn initial_offset(&mut self) -> Result<Self::Offset>;
+
+    /// Returns the limit on the data of each micro-batch. Spark asks once, 
when the query
+    /// starts. The default, [`ReadLimit::AllAvailable`], reads all the 
available data in
+    /// each micro-batch.
+    fn default_read_limit(&self) -> Result<ReadLimit> {
+        Ok(ReadLimit::AllAvailable)
+    }
+
+    /// Returns the end of the next micro-batch: the offset of the most recent 
data after
+    /// [`LatestOffsetInfo::start`], within its limit, and not beyond its end 
of the run.
+    /// Return `start` when there is no new data. When there is, return an 
offset after
+    /// `start`, even if the next unit of data, such as a file, is larger than 
the limit:
+    /// Spark sees no new data otherwise, and never reads further.
+    ///
+    /// With a limit, Spark also asks without a limit for some micro-batches, 
to report the
+    /// progress of the query, so do not count the calls as micro-batches, or 
reserve data in
+    /// them.
+    fn latest_offset(&mut self, info: LatestOffsetInfo<Self::Offset>) -> 
Result<Self::Offset>;
+
+    /// Plans the micro-batch between the progress boundaries 
[`MicroBatchInfo::start`] and
+    /// [`MicroBatchInfo::end`], using the connector's mapping from offsets to 
records.
+    fn plan(&mut self, info: MicroBatchInfo<Self::Offset>) -> 
Result<ScanPlan<Self::Factory>>;
+
+    /// Tells the stream that Spark has processed the data represented by the 
progress boundary
+    /// [`CommitOffsetInfo::end`] and will not read that data again, so the 
stream can release it.
+    fn commit(&mut self, _info: CommitOffsetInfo<Self::Offset>) -> Result<()> {
+        Ok(())
+    }
+}
+
+/// A limit on the data of a micro-batch.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum ReadLimit {
+    /// All the available data.
+    AllAvailable,
+    /// A maximum number of rows, from 1 through [`i64::MAX`]. The SDK rejects 
values outside
+    /// this range at the native ABI boundary. A stream may exceed this limit 
when its next
+    /// unit of data is larger, as described by 
[`MicroBatchStream::latest_offset`].
+    MaxRows(u64),
+}
+
+/// What Spark passes to ask a stream for its latest offset.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct LatestOffsetInfo<O> {
+    /// The starting progress boundary: the end of the previous micro-batch, 
or the initial
+    /// offset.
+    pub start: O,
+    /// The limit on the data after `start`: that of
+    /// [`MicroBatchStream::default_read_limit`], or 
[`ReadLimit::AllAvailable`] when Spark
+    /// reads all the available data, such as for the progress of the query or 
with
+    /// `Trigger.Once`.
+    pub limit: ReadLimit,
+    /// With `Trigger.AvailableNow` and a limit, the end of the run: the 
latest offset must not
+    /// go beyond it, so that the run reads the data that was available when 
it started. It is
+    /// not the end of the next micro-batch. `None` otherwise.
+    pub run_end: Option<O>,
+}
+
+impl<O> LatestOffsetInfo<O> {
+    /// A request without a limit, made outside Spark, for example in a test. 
Set
+    /// [`limit`](Self::limit) and [`run_end`](Self::run_end) for other 
requests.
+    pub fn new(start: O) -> Self {
+        Self {
+            start,
+            limit: ReadLimit::AllAvailable,
+            run_end: None,
+        }
+    }
+}
+
+/// What Spark passes to plan a micro-batch: the offsets that delimit its data.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct MicroBatchInfo<O> {
+    /// The starting progress boundary: the end of the previous micro-batch, 
or the initial
+    /// offset. See [`MicroBatchStream`]'s offset contract for how boundaries 
map to records.
+    pub start: O,
+    /// The ending progress boundary, which 
[`MicroBatchStream::latest_offset`] returned.
+    pub end: O,
+}
+
+impl<O> MicroBatchInfo<O> {
+    /// The information of a micro-batch planned outside Spark, for example in 
a test.
+    pub fn new(start: O, end: O) -> Self {
+        Self { start, end }
+    }
+}
+
+/// What Spark passes to commit the data of a stream.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct CommitOffsetInfo<O> {
+    /// The progress boundary of the processed data, which Spark will not read 
again.
+    pub end: O,
+}
+
+impl<O> CommitOffsetInfo<O> {
+    /// The information of a commit made outside Spark, for example in a test.
+    pub fn new(end: O) -> Self {
+        Self { end }
+    }
+}
+
+// Batch writes: a BatchWrite coordinates the write on the driver, and a 
DataWriterFactory
+// opens a DataWriter for each task attempt on the executors.
+
+/// What Spark passes to create a batch write.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct WriteInfo {
+    /// The schema of the data to write.
+    pub schema: SchemaRef,
+    /// How the write changes the destination.
+    pub mode: WriteMode,
+}
+
+impl WriteInfo {
+    /// The information of a write created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, mode: WriteMode) -> Self {
+        Self { schema, mode }
+    }
+}
+
+/// How a write, or the write of a micro-batch, changes the destination.
+///
+/// New modes may be added. The SDK passes a mode only when the source instance
+/// has the matching capability, so a source never receives a mode it did not
+/// opt in to; a wildcard arm can return an error.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum WriteMode {
+    Append,
+    /// Replace existing data at driver commit, never at writer creation.
+    Truncate,
+}
+
+/// A driver coordinator for one batch write, which also creates the 
serializable
+/// configuration of its task writers.
+///
+/// Keep irreversible publication, including removing overwritten data, in 
commit.
+/// Drop releases resources; it must not publish data or perform fallible 
flushing.
+///
+/// # Lifecycle
+///
+/// Spark guarantees the following callback order:
+///
+/// - `new_writer_factory` runs once, right after [`DataSource::new_write`], 
before any task
+///   opens a writer. When it fails, the SDK cannot serialize its factory, or 
Spark cannot
+///   copy the serialized factory, for example when it is too large, the write 
fails and
+///   the coordinator is dropped without `abort`, so Drop must also release 
what only this
+///   write staged.
+/// - `commit` runs at most once, when every task succeeded. The SDK fails the 
write
+///   without calling it when a task message cannot be decoded.
+/// - `abort` runs at most once, never after a successful `commit`. It follows 
a failed
+///   `commit`, or a failed task, also when computing the data to write failed.
+/// - Drop runs exactly once, otherwise when Spark closes the writer: right 
after a
+///   successful `commit` or after `abort`, or, for a write that Spark neither 
commits nor
+///   aborts, possibly late and on another thread.
+/// - A panic in any method is reported as that method's failure.
+///
+/// These guarantees do not determine the outcome of a remote transaction. A 
destination
+/// may publish the write even when `commit` returns an error, for example if 
its
+/// acknowledgement is lost. Use a durable operation identity to check the 
destination's
+/// outcome and make commit and cleanup idempotent. `abort` and Drop must 
preserve published
+/// output, including output whose commit was not acknowledged. If the outcome 
cannot be
+/// resolved, leave potentially published data intact for later recovery.
+pub trait BatchWrite: Send + 'static {
+    /// The configuration from which each task attempt opens its writer.
+    type Factory: DataWriterFactory<Message = Self::Message>;
+
+    /// The message with which a task attempt reports its staged output to the 
driver.
+    type Message: Serialize + DeserializeOwned + Send + 'static;
+
+    /// Whether the write supports [`WriteMode::Truncate`], for the save mode 
"overwrite",
+    /// which adds the `BATCH_TRUNCATE` capability.
+    const SUPPORTS_TRUNCATE: bool = false;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Returns the configuration of the task writers, which the SDK 
serializes for them.
+    /// Include a unique operation ID when needed; Spark supplies no batch 
query ID.
+    fn new_writer_factory(&self) -> Result<Self::Factory>;
+
+    /// Publish only the winning attempt from each input partition, whose 
messages
+    /// [`CommitInfo::messages`] has. Task retries and speculative attempts 
can stage other
+    /// data that must not be published.
+    fn commit(&mut self, info: CommitInfo<Self::Message>) -> Result<()>;
+
+    /// Abort after input, task, or driver commit failure, with the messages 
that reached the
+    /// driver in [`AbortInfo::messages`]. Executor loss can leave orphaned 
staged data; plan
+    /// for its cleanup.
+    fn abort(&mut self, info: AbortInfo<Self::Message>) -> Result<()>;
+}
+
+/// What Spark passes to commit a batch write.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct CommitInfo<M> {
+    /// The message of the winning task attempt of each input partition, at 
the position of
+    /// its partition.
+    pub messages: Vec<M>,
+}
+
+impl<M> CommitInfo<M> {
+    /// The information of a commit made outside Spark, for example in a test.
+    pub fn new(messages: Vec<M>) -> Self {
+        Self { messages }
+    }
+}
+
+/// What Spark passes to abort a batch write.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct AbortInfo<M> {
+    /// The message of each input partition, at the position of its partition, 
or `None` for a
+    /// partition whose commit message did not reach the driver, or cannot be 
decoded.
+    pub messages: Vec<Option<M>>,
+}
+
+impl<M> AbortInfo<M> {
+    /// The information of an abort made outside Spark, for example in a test.
+    pub fn new(messages: Vec<Option<M>>) -> Self {
+        Self { messages }
+    }
+}
+
+/// Serializable configuration for independent task-attempt writers, which
+/// [`BatchWrite::new_writer_factory`] or 
[`StreamingWrite::new_writer_factory`] creates.
+///
+/// Open connections and files in open, not in the factory. A returned writer
+/// cannot borrow this temporary factory, but may retain the context until
+/// close. Callbacks can move between threads sequentially; writers must be 
Send.
+pub trait DataWriterFactory: Serialize + DeserializeOwned + Send + 'static {
+    type Message: Serialize + DeserializeOwned + Send + 'static;
+
+    fn open<'task>(
+        &self,
+        context: WriterContext<'task>,
+    ) -> Result<PartitionWriter<'task, Self::Message>>;
+}
+
+/// What a task writer receives when it opens.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct WriterContext<'task> {
+    /// The schema of the batches to write, as in [`WriteInfo::schema`].
+    pub schema: SchemaRef,
+    /// The Spark task's partition ID. Its winning commit message has this 
position in
+    /// [`CommitInfo::messages`] or [`StreamingCommitInfo::messages`].
+    pub partition_id: i32,
+    /// The task attempt that writes.
+    pub task: TaskContext<'task>,
+    /// The epoch of the micro-batch of a streaming write, or `None` for a 
batch write.
+    pub epoch_id: Option<i64>,
+}
+
+impl<'task> WriterContext<'task> {
+    /// The context of a batch writer opened outside Spark, for example in a 
test. Set
+    /// [`epoch_id`](Self::epoch_id) for a streaming writer.
+    pub fn new(schema: SchemaRef, partition_id: i32, task: TaskContext<'task>) 
-> Self {
+        Self {
+            schema,
+            partition_id,
+            task,
+            epoch_id: None,
+        }
+    }
+}
+
+/// One task attempt's writer. Spark drops it after commit or abort.
+///
+/// # Lifecycle
+///
+/// Spark guarantees the following callback order:
+///
+/// - `write` runs zero or more times, before `commit` or `abort`, and never 
after a
+///   call has failed.
+/// - `commit` runs at most once, never after a failed `write` or after 
`abort`.
+/// - `abort` runs at most once, never after a `commit` whose message reached 
Spark.
+///   It may follow a failed `write` or `commit`, including a `commit` that 
returned
+///   a message that the SDK could not serialize, so it must handle a task 
attempt
+///   that already finished its output.
+/// - Drop runs exactly once when Spark closes the writer, possibly without
+///   `commit` or `abort`.
+/// - The writer of a task attempt that Spark kills, such as a speculative 
one, may still
+///   write, abort, and drop after the driver committed or aborted the write.
+/// - A panic in any method is reported as that method's failure.
+pub trait DataWriter: Send {
+    type Message;
+
+    /// Takes ownership of an imported Arrow batch, which may be retained 
after this call,
+    /// but not after the writer is dropped: its buffers belong to the data 
writer of Spark,
+    /// and the ABI requires the library to release them before Spark closes 
the writer, so do
+    /// not pass the batch to a thread or a value that outlives the writer. 
Spark cannot free a
+    /// batch that is still retained when it closes the writer: it logs an 
error, and the memory
+    /// stays allocated until the batch is dropped. It has the schema of
+    /// [`WriterContext::schema`], and at most 
`spark.sql.execution.arrow.maxRecordsPerBatch`
+    /// rows. When Spark writes the batches of a native scan without 
converting them to rows,
+    /// it copies their values as the scan returned them, without the checks 
of a conversion,
+    /// such as the precision of a decimal. The SDK validates each batch 
before this call, and
+    /// fails the write of one that Arrow rejects, such as a Spark string that 
is not UTF-8.

Review Comment:
   Since 40ab9e7 this is no longer true for nullability: `validate` (write.rs 
L266-L284) skips the nullability checks of `validate_full`, so a batch that 
Arrow rejects, such as one with a null element under a null slot of a list 
whose element is not nullable, now reaches `write` (the test at write.rs 
L394-L413 passes exactly that). The README says so at L296-L297, but this 
rustdoc is what a connector reads. Could it say the same: the SDK validates the 
layout and values of each batch, not its nullability, so a field that is not 
nullable can still hold nulls under a null parent? The `import` comment 
(write.rs L254-L256, "validates it fully") needs the same change, as does the 
write-side validation that viirya asked the description to mention.



##########
sql/native/rust/README.md:
##########
@@ -0,0 +1,568 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+
+# Rust native data source SDK prototype
+
+This experimental SDK implements **batch and micro-batch streaming reads, with 
admission
+control, and batch and streaming writes** over version 1 of the C ABI of 
native data sources,
+[`spark_datasource.h`][header], which Spark 4.4.0 introduces. Spark calls the 
library through
+the Java Foreign Function and Memory (FFM) API, so running a library in Spark 
requires Java 22
+or newer on the driver and executors. The [guide of native data 
sources][guide] describes the
+ABI.
+
+The Rust and C tests run independently of Spark and Java. The workspace is not
+part of Maven/SBT and introduces no Rust requirement for building Spark. This 
is
+an API prototype, not a compatibility commitment.
+
+The crate, `spark-datasource`, after `spark_datasource.h`, is not published 
yet: depend on it
+with a path dependency on a Spark source tree, as the examples do, until 
SPARK-61307 publishes
+it to crates.io. It is versioned on its own, from 0.x, and may need a breaking 
release in any
+release of Spark: for a new major version of Arrow, whose types it exposes, or 
for a new kind
+of operation, which adds an associated type to `DataSource` that every 
connector must name.
+Growth within an operation can preserve Rust source compatibility, for example 
by adding
+fields to non-exhaustive input structs under the conditions described below. 
The crate
+supports version 1 of the ABI, which Spark supports from 4.4.0 in all the 
releases of Spark 4.
+
+The API uses the types of Arrow 58, such as `RecordBatch`, `SchemaRef`, and 
`ArrowError`, so
+a connector must use the same major version of Arrow: the SDK re-exports the 
crates as
+`spark_datasource::arrow_array` and `spark_datasource::arrow_schema`. 
Upgrading the
+major version of Arrow is a breaking change of the SDK.
+
+The [Range connector][range] is a separate workspace member under
+`examples/src/main/rust/native-data-source`, with a C integration test, 
packaging
+helper, and Spark smoke script. The [file sink example][sink] is a separate 
write-only
+connector. All crates share this directory's lockfile and `target` directory. 
Cargo commands
+select the SDK by default; use `--workspace` to include the examples.
+
+## Connector API and lifecycle
+
+A connector implements [`DataSource`](src/lib.rs) for construction, schema 
discovery,
+its operations, and optional capability restrictions. `DataSource::new` 
receives a
+`CreateInfo` with the name of the data source and its options. Spark can 
create and
+immediately drop a source just to discover capabilities; schema inference or an
+operation need not follow.
+
+Four associated types name the operations that the source implements, and
+`Unsupported` stands for one that it does not implement:
+
+```rust
+impl DataSource for RangeSource {
+    type ScanBuilder = RangeScan; // batch reads, created by new_scan
+    type MicroBatchStream = RangeStream; // streaming reads, by 
new_micro_batch_stream
+    type BatchWrite = Unsupported; // no batch writes
+    type StreamingWrite = Unsupported; // no streaming writes
+    // new, infer_schema, new_scan, and new_micro_batch_stream
+}
+```
+
+Read support uses three pieces:
+
+* `DataSource::new_scan`: create an independent scan builder from a 
`ScanInfo`, which
+  carries the schema to read.
+* `ScanBuilder`: negotiate the limit and the columns to read, then consume 
itself
+  in `plan()` to return a typed `ScanPlan<Factory>`.
+* `PartitionReaderFactory`: serialize executor configuration and open one lazy 
reader,
+  an iterator of Arrow batches, from a typed partition and a `ReaderContext`, 
which
+  carries the schema to read and a borrowed `TaskContext`.
+
+Streaming reads reuse the executor side: `DataSource::new_micro_batch_stream` 
creates a
+`MicroBatchStream` from a `MicroBatchStreamInfo`, which carries the columns to 
read and the
+location of the checkpoint of the source, and the stream plans each 
micro-batch as a
+`ScanPlan` of a `PartitionReaderFactory`; see
+[Streaming reads and writes](#streaming-reads-and-writes).
+
+Write support is independent: a write-only connector sets `ScanBuilder` and
+`MicroBatchStream` to `Unsupported` and implements `DataSource::new_write`, 
`BatchWrite`,
+`DataWriterFactory`, and `DataWriter`. Streaming writes add
+`DataSource::new_streaming_write` and `StreamingWrite`, with the same task 
writers. The
+write lifecycle is described below.
+
+The inputs of these methods are `#[non_exhaustive]` structs: `*Info` structs 
on the driver
+(`CreateInfo`, `ScanInfo`, `MicroBatchStreamInfo`, `LatestOffsetInfo`, 
`MicroBatchInfo`,
+`CommitOffsetInfo`, `WriteInfo`, `CommitInfo`, `AbortInfo`, 
`StreamingWriteInfo`,
+`StreamingCommitInfo`, and `StreamingAbortInfo`), `*Context` structs, which 
carry the live
+`TaskContext`, on the executors (`ReaderContext` and `WriterContext`), and 
`HostInfo`, which
+`DataSource::init` receives in every JVM that loads the library, executors 
included. Fields
+may be added to them: construct them with `new`, as in tests, and destructure 
them with `..`.

Review Comment:
   `HostInfo` has no `new`: it implements `Default` (host.rs L52-L60), so a 
test outside the crate builds one with `HostInfo::default()` and then sets its 
public fields. The other structs in this list all have a public `new`. Could 
the sentence say so for `HostInfo`, or could it get a `new` like the others?



##########
sql/native/rust/README.md:
##########
@@ -0,0 +1,568 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+
+# Rust native data source SDK prototype
+
+This experimental SDK implements **batch and micro-batch streaming reads, with 
admission
+control, and batch and streaming writes** over version 1 of the C ABI of 
native data sources,
+[`spark_datasource.h`][header], which Spark 4.4.0 introduces. Spark calls the 
library through
+the Java Foreign Function and Memory (FFM) API, so running a library in Spark 
requires Java 22
+or newer on the driver and executors. The [guide of native data 
sources][guide] describes the
+ABI.
+
+The Rust and C tests run independently of Spark and Java. The workspace is not
+part of Maven/SBT and introduces no Rust requirement for building Spark. This 
is
+an API prototype, not a compatibility commitment.
+
+The crate, `spark-datasource`, after `spark_datasource.h`, is not published 
yet: depend on it
+with a path dependency on a Spark source tree, as the examples do, until 
SPARK-61307 publishes
+it to crates.io. It is versioned on its own, from 0.x, and may need a breaking 
release in any
+release of Spark: for a new major version of Arrow, whose types it exposes, or 
for a new kind
+of operation, which adds an associated type to `DataSource` that every 
connector must name.
+Growth within an operation can preserve Rust source compatibility, for example 
by adding
+fields to non-exhaustive input structs under the conditions described below. 
The crate
+supports version 1 of the ABI, which Spark supports from 4.4.0 in all the 
releases of Spark 4.
+
+The API uses the types of Arrow 58, such as `RecordBatch`, `SchemaRef`, and 
`ArrowError`, so
+a connector must use the same major version of Arrow: the SDK re-exports the 
crates as
+`spark_datasource::arrow_array` and `spark_datasource::arrow_schema`. 
Upgrading the
+major version of Arrow is a breaking change of the SDK.
+
+The [Range connector][range] is a separate workspace member under
+`examples/src/main/rust/native-data-source`, with a C integration test, 
packaging
+helper, and Spark smoke script. The [file sink example][sink] is a separate 
write-only
+connector. All crates share this directory's lockfile and `target` directory. 
Cargo commands
+select the SDK by default; use `--workspace` to include the examples.
+
+## Connector API and lifecycle
+
+A connector implements [`DataSource`](src/lib.rs) for construction, schema 
discovery,
+its operations, and optional capability restrictions. `DataSource::new` 
receives a
+`CreateInfo` with the name of the data source and its options. Spark can 
create and
+immediately drop a source just to discover capabilities; schema inference or an
+operation need not follow.
+
+Four associated types name the operations that the source implements, and
+`Unsupported` stands for one that it does not implement:
+
+```rust
+impl DataSource for RangeSource {
+    type ScanBuilder = RangeScan; // batch reads, created by new_scan
+    type MicroBatchStream = RangeStream; // streaming reads, by 
new_micro_batch_stream
+    type BatchWrite = Unsupported; // no batch writes
+    type StreamingWrite = Unsupported; // no streaming writes
+    // new, infer_schema, new_scan, and new_micro_batch_stream
+}
+```
+
+Read support uses three pieces:
+
+* `DataSource::new_scan`: create an independent scan builder from a 
`ScanInfo`, which
+  carries the schema to read.
+* `ScanBuilder`: negotiate the limit and the columns to read, then consume 
itself
+  in `plan()` to return a typed `ScanPlan<Factory>`.
+* `PartitionReaderFactory`: serialize executor configuration and open one lazy 
reader,
+  an iterator of Arrow batches, from a typed partition and a `ReaderContext`, 
which
+  carries the schema to read and a borrowed `TaskContext`.

Review Comment:
   `ReaderContext` also carries `partition_index` (lib.rs L384-L387), which 
L149-L151 describe, but this sentence lists only the schema to read and the 
task. Could it say "which carries the schema to read, the index of the 
partition in its plan, and a borrowed `TaskContext`"?



##########
sql/native/rust/src/write.rs:
##########
@@ -0,0 +1,414 @@
+// 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_data::ArrayData;
+use arrow_schema::{ArrowError, 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::{
+    AbortInfo, BatchWrite, CommitInfo, DataWriter, DataWriterFactory, 
PartitionWriter, Result,
+    StreamingAbortInfo, StreamingCommitInfo, 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 new_writer_factory(&self) -> Result<W::Factory> {
+        self.0.new_writer_factory()
+    }
+
+    fn commit(&mut self, info: StreamingCommitInfo<W::Message>) -> Result<()> {
+        self.0.commit(CommitInfo::new(info.messages))
+    }
+
+    fn abort(&mut self, info: StreamingAbortInfo<W::Message>) -> Result<()> {
+        self.0.abort(AbortInfo::new(info.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 close, including after a failed 
commit, which
+/// Spark aborts next. Spark closes the writer right after it commits or 
aborts the write.
+pub struct DriverWriter<C: StreamingWrite> {
+    coordinator: Option<C>,
+}
+
+impl<C: StreamingWrite> DriverWriter<C> {
+    /// Wraps a coordinator, with the state that its task writers need: its 
serialized
+    /// writer factory. On failure, the coordinator is dropped.
+    pub fn create(coordinator: C) -> Result<(Box<dyn DriverWrite>, Vec<u8>)> {
+        let writer = Self {
+            coordinator: Some(coordinator),
+        };
+        // The factory's destructor is connector code too, so it runs in 
provider_call.
+        let state = provider_call(|| 
encode(&writer.coordinator().new_writer_factory()?))?;
+        Ok((Box::new(writer), state))
+    }
+
+    fn coordinator(&self) -> &C {
+        self.coordinator.as_ref().expect("coordinator is present")
+    }
+
+    fn coordinator_mut(&mut self) -> &mut C {
+        self.coordinator.as_mut().expect("coordinator is present")
+    }
+}
+
+impl<C: StreamingWrite> DriverWrite for DriverWriter<C> {
+    fn commit(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> 
Result<()> {
+        let messages = messages
+            .iter()
+            .map(|message| decode(message.ok_or("missing committed task 
message")?))
+            .collect::<Result<Vec<_>>>()?;
+        self.coordinator_mut()
+            .commit(StreamingCommitInfo::new(epoch_id, messages))
+    }
+
+    fn abort(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> 
Result<()> {
+        // Abort is the cleanup path: a message that cannot be decoded is 
passed as None
+        // instead of preventing the coordinator from cleaning up.
+        let messages = messages
+            .iter()
+            .enumerate()
+            .map(|(partition, message)| match decode((*message)?) {
+                Ok(message) => Some(message),
+                Err(error) => {
+                    log::warn!(
+                        "Aborting a write without the commit message of 
partition \
+                         {partition}, which cannot be decoded: {}",
+                        describe(&*error)
+                    );
+                    None
+                }
+            })
+            .collect();
+        self.coordinator_mut()
+            .abort(StreamingAbortInfo::new(epoch_id, messages))
+    }
+}
+
+impl<C: StreamingWrite> Drop for DriverWriter<C> {
+    fn drop(&mut self) {
+        // A panic of the coordinator's Drop is logged instead of unwinding 
into close.
+        if let Some(coordinator) = self.coordinator.take() {
+            drop_provider(coordinator);
+        }
+    }
+}
+
+/// A task writer that encodes its own commit message, so that one handle type 
holds the
+/// writers of batch and streaming writes, whatever their messages.
+trait TaskWriter: Send {
+    fn write(&mut self, batch: RecordBatch) -> Result<()>;
+
+    fn commit(&mut self) -> Result<Vec<u8>>;
+
+    fn abort(&mut self) -> Result<()>;
+}
+
+impl<M: Serialize> TaskWriter for PartitionWriter<'_, M> {
+    fn write(&mut self, batch: RecordBatch) -> Result<()> {
+        DataWriter::write(&mut **self, batch)
+    }
+
+    fn commit(&mut self) -> Result<Vec<u8>> {
+        encode(&DataWriter::commit(&mut **self)?)
+    }
+
+    fn abort(&mut self) -> Result<()> {
+        DataWriter::abort(&mut **self)
+    }
+}
+
+struct TaskState<'task> {
+    writer: Option<Box<dyn TaskWriter + 'task>>,
+    // The struct type of the arrays that write gets: the schema that 
create_data_writer got.
+    data_type: DataType,
+}
+
+impl TaskState<'_> {
+    fn writer(&mut self) -> &mut (dyn TaskWriter + '_) {
+        self.writer.as_deref_mut().expect("writer is present")
+    }
+}
+
+impl Drop for TaskState<'_> {
+    fn drop(&mut self) {
+        if let Some(writer) = self.writer.take() {
+            drop_provider(writer);
+        }
+    }
+}
+
+/// Restores the task writer of a batch write, with factory `B`, or of a 
micro-batch, with
+/// factory `S`, without creating or consulting any driver registry. The epoch 
ID tells them
+/// apart: it is -1 for a batch write.
+///
+/// # Safety
+/// `task` must satisfy TaskContext::from_raw and remain valid until 
close_task.
+/// The returned handle must never be used concurrently, and must be closed 
exactly
+/// once while the plugin stays loaded.
+pub unsafe fn open<B: DataWriterFactory, S: DataWriterFactory>(
+    task: *const SparkDsTaskContext,
+    schema: SchemaRef,
+    state: &[u8],
+    epoch_id: i64,
+) -> Result<*mut c_void> {
+    match epoch_id {
+        -1 => unsafe { open_writer::<B>(task, schema, state, None) },
+        epoch_id if epoch_id >= 0 => unsafe {
+            open_writer::<S>(task, schema, state, Some(epoch_id))
+        },
+        _ => Err(format!("invalid epoch ID {epoch_id}").into()),
+    }
+}
+
+/// # Safety
+/// As for open.
+unsafe fn open_writer<F: DataWriterFactory>(
+    task: *const SparkDsTaskContext,
+    schema: SchemaRef,
+    state: &[u8],
+    epoch_id: Option<i64>,
+) -> Result<*mut c_void> {
+    validate_schema(&schema)?;
+    let factory: F = decode(state)?;
+    let (task, partition_id) = unsafe { TaskContext::from_raw(task)? };
+    let data_type = DataType::Struct(schema.fields().clone());
+    let mut context = WriterContext::new(schema, partition_id, task);
+    context.epoch_id = epoch_id;
+    let opened = provider_call(|| factory.open(context));
+    // Keep guarded writer destruction in place before dropping the temporary
+    // factory, whose destructor is connector code too.
+    let state = opened.map(|writer| {
+        Box::new(TaskState {
+            writer: Some(Box::new(writer)),
+            data_type,
+        })
+    });
+    let factory_drop = provider_call(|| {
+        drop(factory);
+        Ok(())
+    });
+    let state = state?;
+    factory_drop?;
+    Ok(Box::into_raw(state).cast())
+}
+
+/// # Safety
+/// `handle` must be a live handle from open, accessed without concurrency.
+unsafe fn task_state<'a>(handle: *mut c_void) -> Result<&'a mut TaskState<'a>> 
{
+    abi::require_output(handle)?;
+    Ok(unsafe { &mut *handle.cast::<TaskState<'a>>() })
+}
+
+/// Imports owned Arrow data, with the schema of the writer, and passes it to 
the task writer.
+///
+/// # Safety
+/// `handle` must follow open's contract. The array must be valid Arrow C data 
of the schema
+/// of the writer, which this call may move.
+pub unsafe fn write_batch(handle: *mut c_void, array: *mut ArrowArray) -> 
Result<()> {
+    let state = unsafe { task_state(handle)? };
+    abi::require_output(array)?;
+    let array = unsafe { import(ArrowArray::from_raw(array), 
&state.data_type)? };
+    if array.null_count() != 0 {
+        return Err("write input cannot contain null rows".into());
+    }
+    state.writer().write(RecordBatch::from(array))
+}
+
+/// Imports a batch to write. Arrow does not validate the C data that it 
imports, which the safe
+/// accessors of the connector rely on, so this validates it fully: a Spark 
string may hold bytes
+/// that are not UTF-8, such as those of a cast from binary, which a Rust 
`&str` must not.
+///
+/// # Safety
+/// As for write_batch: the array must be Arrow C data of `data_type`.
+unsafe fn import(array: ArrowArray, data_type: &DataType) -> 
Result<StructArray> {
+    let data = unsafe { ffi::from_ffi_and_data_type(array, data_type.clone())? 
};
+    validate(&data).map_err(|e| format!("write input is not valid Arrow data: 
{e}"))?;
+    Ok(StructArray::from(data))
+}
+
+/// Validates `data` and its children as `ArrayData::validate_full` does, 
except that it does not
+/// check nulls against the nullability of fields. Arrow rejects any null in 
the child of a list
+/// or map whose element is not nullable, even one under a null slot, a layout 
that Spark accepts
+/// from a native scan: Spark checks nullability itself, masked by the parent, 
before it passes a
+/// batch to write.
+fn validate(data: &ArrayData) -> std::result::Result<(), ArrowError> {
+    data.validate()?;
+    if let Some(nulls) = data.nulls() {
+        let actual = nulls.len() - nulls.inner().count_set_bits();
+        if actual != nulls.null_count() {
+            return Err(ArrowError::InvalidArgumentError(format!(
+                "null count {} does not match the {actual} nulls of the 
validity buffer",
+                nulls.null_count()
+            )));
+        }
+    }

Review Comment:
   Only the UTF-8 tests (L364-L392) make a check here fail, through 
`validate_values` and the recursion. Deleting `data.validate()?` (L272) or the 
null count check (L273-L281) still passes every test, and the new test 
(L394-L413) covers a list but not a map. Could you add cases that only these 
lines reject, such as a struct column whose child is shorter than the struct 
and a column whose null count disagrees with its validity buffer, plus a map 
with a null value under a null slot?



##########
sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h:
##########
@@ -833,8 +838,8 @@ typedef struct SparkDsLibrary {
                            SparkDsSink add_partition, SparkDsSink set_state, 
void* sink);
 
   /*
-   * Tells the library that Spark has processed all the data up to and 
including an offset, and
-   * will not ask for it again.
+   * Tells the library that Spark has processed the data represented by an 
offset's progress
+   * boundary, and will not ask for that data again.

Review Comment:
   A progress boundary does not represent data, so this no longer says which 
data Spark processed; before 04b33fd it was "all the data up to and including 
an offset". With the `[start, end)` ranges of L521-L524, it is all the data 
before the boundary. Could this say "Spark has processed all the data before an 
offset's progress boundary", with the same wording in 
`MicroBatchStream::commit` (lib.rs L520-L521) and the README (L378-L379)?



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