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


##########
sql/native/rust/src/abi.rs:
##########
@@ -0,0 +1,887 @@
+// 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};
+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,
+    }
+}
+
+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 every field of version 1 
of the ABI: fields
+/// are only appended to the structures, so a shorter one is an error, not 
partly read.
+///
+/// # Safety
+/// A non-null pointer must address a live structure whose first field is its 
size.
+pub unsafe fn input<T: Copy>(pointer: *const T) -> Result<T> {
+    let size = unsafe { struct_size(pointer)? };
+    if size < size_of::<T>() as i64 {

Review Comment:
   `input` rejects a struct shorter than `size_of::<T>()`, the size of the 
SDK's binding. That matches 4.4.0 today, but within version 1 Spark may append 
fields, and "a library must only read the fields that fit in the size of a 
struct that Spark passes, and only set those of a struct that it fills" 
([spark_datasource.h 
L216-L222](https://github.com/apache/spark/blob/24bf9678b2ef1f7c25e4621d3d71085ffd9d3763/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h#L216-L222)).
 Once the SDK binds an appended field, a connector built with it fails on an 
earlier 4.4.x with "has N bytes, fewer than in version 1", although that Spark 
implements version 1, and the README says that a new field of an info struct 
does not break connectors (README L36-L38). `set_read_limit` (L636) does the 
same for the struct it fills. Could the minimum be each struct's size in 4.4.0, 
with fields appended later read only when they fit, as `field` (L439) does for 
`SparkDsHost`? Today the mi
 nimum would be the same, so nothing else changes.



##########
.github/workflows/build_and_test.yml:
##########
@@ -1425,3 +1428,33 @@ jobs:
           cd ui-test
           npm install --save-dev
           node --experimental-vm-modules node_modules/.bin/jest
+
+  rust-sdk:
+    needs: [precondition]
+    if: fromJson(needs.precondition.outputs.required).rust-sdk == 'true'

Review Comment:
   Pushes to apache/spark pass an explicit `jobs` list from build_main.yml, 
which has `"ui": "true"` but no `rust-sdk` ([build_main.yml 
L39-L61](https://github.com/apache/spark/blob/24bf9678b2ef1f7c25e4621d3d71085ffd9d3763/.github/workflows/build_main.yml#L39-L61)).
 So this condition is false in the sampled post-merge builds, which are meant 
to run the full job matrix, and the job runs only in fork builds such as this 
PR's. Could you add `"rust-sdk": "true"` there too?



##########
sql/native/rust/src/write.rs:
##########
@@ -0,0 +1,290 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License. You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Driver write coordination and task-local writers restored from serialized 
state, for batch
+//! writes and for the writes of micro-batches.
+
+use std::ffi::c_void;
+
+use arrow_array::{ffi, Array, RecordBatch, StructArray};
+use arrow_schema::{DataType, SchemaRef};
+use serde::Serialize;
+
+use crate::abi::{self, ArrowArray, SparkDsTaskContext};
+use crate::bridge::stream::validate_schema;
+use crate::bridge::{decode, describe, drop_provider, encode, provider_call};
+use crate::{
+    BatchWrite, DataWriter, DataWriterFactory, PartitionWriter, Result, 
StreamingWrite,
+    TaskContext, WriterContext,
+};
+
+/// A batch write, which a driver writer drives as a streaming write whose 
epoch ID is always
+/// -1 and is ignored.
+pub struct Batch<W>(pub W);
+
+impl<W: BatchWrite> StreamingWrite for Batch<W> {
+    type Factory = W::Factory;
+    type Message = W::Message;
+
+    fn writer_factory(&self) -> Result<W::Factory> {
+        self.0.writer_factory()
+    }
+
+    fn commit(&mut self, _: i64, messages: Vec<W::Message>) -> Result<()> {
+        self.0.commit(messages)
+    }
+
+    fn abort(&mut self, _: i64, messages: Vec<Option<W::Message>>) -> 
Result<()> {
+        self.0.abort(messages)
+    }
+}
+
+/// A driver writer that decodes its own commit messages, so that one handle 
type holds the
+/// driver writers of batch writes and of the writes of micro-batches, which 
share the writer
+/// handles of the ABI.
+pub trait DriverWrite: Send {
+    fn commit(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> 
Result<()>;
+
+    fn abort(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> 
Result<()>;
+}
+
+/// The driver keeps this coordinator until a successful commit or an abort, 
after which Spark

Review Comment:
   SPARK-61284 
([f093bdf](https://github.com/apache/spark/commit/f093bdfa9ad47ad10d77d90e6515a480dff16446))
 is in this branch since the merge of master in 06d77a0: Spark now closes a 
stream writer once it committed or aborted its micro-batch, and closes one that 
it never finished before the next `create_writer` ([spark_datasource.h 
L120-L125](https://github.com/apache/spark/blob/24bf9678b2ef1f7c25e4621d3d71085ffd9d3763/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h#L120-L125)).
 So the reason given here, "such as a stream writer after the next micro-batch 
created its own", no longer applies, nor does the order in the comment at 
tests/streaming.rs L845-L846. Do you still plan to drop the coordinator at 
close again, as in 
https://github.com/apache/spark/pull/59520#discussion_r4519081556? If the early 
drop stays, could both comments give its current reason?



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