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


##########
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:
   Done in f29353269658: Added a unit test in abi.rs that calls `initialize` 
with `abi_version: 0` (expects the version error and a null table), with a 
full-size host (init receives `4.4.0`), and with a size of 12 and a valid 
`spark_version` after it (init receives no version).



##########
sql/native/rust/src/bridge.rs:
##########
@@ -0,0 +1,940 @@
+// 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 = 4;
+
+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,
+        ),
+        (
+            Capabilities::STREAMING_TRUNCATE,
+            <S::StreamingWrite as StreamingWrite>::SUPPORTS_TRUNCATE,
+        ),
+    ]);
+
+    fn insert<T>(&self, handles: &HandleMap<T>, value: T) -> Result<i64> {
+        let handle = self
+            .next_handle
+            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| 
id.checked_add(1))
+            .map_err(|_| "native handle IDs exhausted")?;
+        lock(handles).insert(handle, Arc::new(Mutex::new(value)));
+        Ok(handle)
+    }
+
+    pub fn create(&self, info: CreateInfo) -> Result<(i64, u64)> {
+        self.register_source(S::new(info)?)
+    }
+
+    fn register_source(&self, source: S) -> Result<(i64, u64)> {
+        let capabilities = Self::effective(source.capabilities());
+        let handle = self.insert(
+            &self.sources,
+            SourceState {
+                source,
+                capabilities,
+            },
+        )?;
+        // Every stream supports admission control: its default read limit is 
all the
+        // available data unless it overrides 
MicroBatchStream::default_read_limit.
+        let admission_control = if 
capabilities.contains(Capabilities::MICRO_BATCH_READ) {
+            abi::ADMISSION_CONTROL
+        } else {
+            0
+        };
+        Ok((handle, capabilities.bits() | admission_control))
+    }
+
+    /// Keeps the implemented operations of a declaration, so that a source 
can narrow its
+    /// operations but never add one, and each truncation only with its write.
+    fn effective(declared: Capabilities) -> Capabilities {
+        let mut capabilities = declared.intersection(Self::CAPABILITIES);
+        for (write, truncate) in [
+            (Capabilities::BATCH_WRITE, Capabilities::BATCH_TRUNCATE),

Review Comment:
   Done in f29353269658: Added a `"no_batch_write"` case to the grid in 
tests/batch_write.rs: the source declares everything except `BATCH_WRITE`, and 
the test expects a mask of 0.



##########
sql/native/rust/README.md:
##########
@@ -0,0 +1,544 @@
+<!--
+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, such as a method with a default implementation or 
a field of an
+info struct, does not break connectors. 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, schema, new_scan, and new_micro_batch_stream

Review Comment:
   Done in f29353269658: The README example now says `infer_schema`.



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