tdcmeehan commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4559478583
########## 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: Only the streaming half of this rule is tested (`no_streaming_write` in tests/streaming.rs L550). The grid in tests/batch_write.rs L547 declares only `""`, `"append"` and `"none"`, the source of the bridge unit test has no write, and the sink's readonly test calls `capabilities()` directly. So deleting this entry would let `Capabilities::all().without(Capabilities::BATCH_WRITE)` export `BATCH_TRUNCATE` without `BATCH_WRITE`, and no test would fail. Could that grid get a `"no_batch_write"` case expecting 0, as the streaming one has? ########## 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: No test reaches this check or the size-bounded reads of the host after it. Every host in tests/capabilities.rs, tests/batch_write.rs, tests/streaming.rs and c_abi_smoke.c is full-size with `abi_version = ABI_VERSION`, and the only init failure tested is the `init` hook rejecting the Spark version (tests/capabilities.rs L186-L204). So dropping `version < ABI_VERSION`, or reading `spark_version` and `log` past the host's `size`, would still pass `cargo test`. Could a unit test call `initialize` with `abi_version: 0`, expecting the version error and a null table, and with a `size` of 12 and a valid `spark_version` pointer after it, expecting `init` to get `spark_version: None`? ########## 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: `DataSource::schema` is `infer_schema` now (lib.rs L155), so this names a method the trait doesn't have: ```suggestion // new, infer_schema, new_scan, and new_micro_batch_stream ``` The example in the PR description has the same line. ########## examples/src/main/rust/native-data-sink/src/lib.rs: ########## @@ -0,0 +1,1042 @@ +// 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. + +//! A write-only JSONL sink demonstrating task staging, atomic manifest commits, and +//! exactly-once streaming writes. +//! +//! This example requires one local or shared POSIX filesystem. It is not an +//! object-store connector, a concurrent writer protocol, or a durable table format. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufWriter, ErrorKind, Write}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_datasource::{ + AbortInfo, BatchWrite, Capabilities, CommitInfo, CreateInfo, DataSource, DataWriter, + DataWriterFactory, PartitionWriter, Result, StreamingAbortInfo, StreamingCommitInfo, + StreamingWrite, StreamingWriteInfo, TaskContext, Unsupported, WriteInfo, WriteMode, + WriterContext, +}; + +spark_datasource::export_data_source!(JsonSink); + +static NEXT_ID: AtomicU64 = AtomicU64::new(0); + +/// Construction and capability discovery do not access the filesystem. +pub struct JsonSink { + path: PathBuf, + readonly: bool, +} + +impl DataSource for JsonSink { + // A write-only sink. + type ScanBuilder = Unsupported; + type MicroBatchStream = Unsupported; + type BatchWrite = JsonWrite; + type StreamingWrite = JsonStreamingWrite; + + fn new(info: CreateInfo) -> Result<Self> { + let mut options = info.options; + let path = PathBuf::from( + options + .remove("path") + .ok_or("The path option is required")?, + ); + if !path.is_absolute() { + return Err("The path must be absolute and shared by the driver and executors".into()); + } + let readonly = match options.remove("readonly").as_deref() { + None | Some("false") => false, + Some("true") => true, + _ => return Err("The readonly option must be true or false".into()), + }; + // Spark passes the checkpoint and the name of a streaming query among the options of + // its sink. + options.remove("checkpointlocation"); + options.remove("queryname"); + if !options.is_empty() { + return Err( + format!("Unknown options: {:?}", options.keys().collect::<Vec<_>>()).into(), + ); + } + Ok(Self { path, readonly }) + } + + fn infer_schema(&self) -> Result<SchemaRef> { + Ok(sink_schema()) + } + + fn capabilities(&self) -> Capabilities { + if self.readonly { + // A write-only sink without its writes. + Capabilities::empty() + } else { + Capabilities::all() + } + } + + fn new_write(&self, info: WriteInfo) -> Result<JsonWrite> { + if self.readonly { + return Err("This sink is readonly".into()); + } + validate_schema(&info.schema)?; + JsonWrite::new(self.path.clone(), info.mode) + } + + fn new_streaming_write(&self, info: StreamingWriteInfo) -> Result<JsonStreamingWrite> { + Ok(JsonStreamingWrite { + write: self.new_write(WriteInfo::new(info.schema, info.mode))?, + query_id: info.query_id, + }) + } +} + +fn sink_schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new("label", DataType::Utf8, true), + ])) +} + +fn validate_schema(schema: &Schema) -> Result<()> { + let fields = schema.fields(); + if fields.len() != 2 + || fields[0].name() != "id" + || fields[0].data_type() != &DataType::Int64 + || fields[1].name() != "label" + || fields[1].data_type() != &DataType::Utf8 + { + return Err("Expected columns id BIGINT, label STRING, in that order".into()); + } + Ok(()) +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct DataFile { + path: String, + rows: u64, +} + +#[derive(Debug, Deserialize, Serialize)] +struct Manifest { + version: u32, + files: Vec<DataFile>, + /// The last epoch that each streaming query committed, by the ID of the query. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + epochs: BTreeMap<String, i64>, +} + +impl Default for Manifest { + fn default() -> Self { + Self { + version: 1, + files: Vec::new(), + epochs: BTreeMap::new(), + } + } +} + +fn read_manifest(root: &Path) -> Result<Manifest> { + let file = match File::open(root.join("manifest.json")) { + Ok(file) => file, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Manifest::default()), + Err(error) => return Err(error.into()), + }; + let manifest: Manifest = serde_json::from_reader(file)?; + if manifest.version != 1 { + return Err("Unsupported sink manifest version".into()); + } + for file in &manifest.files { + let components = Path::new(&file.path).components().collect::<Vec<_>>(); + if components.len() != 3 + || components[0] != Component::Normal("objects".as_ref()) + || !components.iter().all(|c| matches!(c, Component::Normal(_))) + { + return Err("Invalid sink manifest data path".into()); + } + } + Ok(manifest) +} + +/// This lock is held for the whole write operation, including all task attempts. +struct WriteLock(PathBuf); + +impl WriteLock { + fn acquire(root: &Path) -> Result<Self> { + let path = root.join(".write-lock"); + match fs::create_dir(&path) { + Ok(()) => Ok(Self(path)), + Err(error) if error.kind() == ErrorKind::AlreadyExists => { + Err("Another write owns .write-lock; concurrent writes are unsupported".into()) + } + Err(error) => Err(error.into()), + } + } +} + +impl Drop for WriteLock { + fn drop(&mut self) { + let _ = fs::remove_dir(&self.0); + } +} + +pub struct JsonWrite { + root: PathBuf, + operation: String, + staging: PathBuf, + objects: PathBuf, + temporary_manifest: PathBuf, + previous: Manifest, + truncate: bool, + committed: bool, + sealed: bool, + lock: Option<WriteLock>, +} + +impl JsonWrite { + fn new(root: PathBuf, mode: WriteMode) -> Result<Self> { + if !cfg!(unix) { + return Err("This demo requires a POSIX filesystem".into()); + } + let truncate = match mode { + WriteMode::Append => false, + WriteMode::Truncate => true, + _ => return Err("Unsupported write mode".into()), + }; + fs::create_dir_all(&root)?; + let lock = WriteLock::acquire(&root)?; + let previous = read_manifest(&root)?; + fs::create_dir_all(root.join(".staging"))?; + fs::create_dir_all(root.join("objects"))?; + let staging = unique_directory(&root.join(".staging"))?; + let operation = staging.file_name().unwrap().to_str().unwrap().to_owned(); + Ok(Self { + objects: root.join("objects").join(&operation), + temporary_manifest: root.join(format!(".manifest-{operation}.json")), + root, + operation, + staging, + previous, + truncate, + committed: false, + sealed: false, + lock: Some(lock), + }) + } + + /// Publishes the winning attempts, and records the epoch of a streaming query. + fn publish( + &mut self, + messages: Vec<CommitMessage>, + epoch: Option<(String, i64)>, + ) -> Result<()> { + let mut filenames = BTreeSet::new(); + for (index, message) in messages.iter().enumerate() { + if message.operation != self.operation + || !is_filename(&message.filename) + || !filenames.insert(message.filename.clone()) + { + return Err("Invalid or duplicate task commit message".into()); + } + // Spark passes the message of partition i at position i. + if usize::try_from(message.partition).ok() != Some(index) { + return Err("A commit message does not match its partition".into()); + } + if !self.staging.join(&message.filename).is_file() { + return Err("A winning task's staged file is missing".into()); + } + } + + // Seal the entire operation directory. New attempts can no longer open + // a staged file, and existing losing files remain invisible to readers. + // A killed attempt that is still running, such as a losing speculative one, + // may have resolved the staging directory just before this rename and create + // its file after the sweep below. That file stays in the sealed directory, + // unlisted, so readers never see it. Such an attempt may also be aborting, and + // its unlink can remove a losing file after the listing below returns it. + fs::rename(&self.staging, &self.objects)?; + self.sealed = true; + for entry in fs::read_dir(&self.objects)? { + let entry = entry?; + if !filenames.contains(&entry.file_name().to_string_lossy().into_owned()) { + match fs::remove_file(entry.path()) { + Ok(()) => {} + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + } + } + + let mut files = if self.truncate { + Vec::new() + } else { + self.previous.files.clone() + }; + files.extend(messages.into_iter().map(|message| DataFile { + path: format!("objects/{}/{}", self.operation, message.filename), + rows: message.rows, + })); + let mut epochs = self.previous.epochs.clone(); + if let Some((query_id, epoch_id)) = epoch { + epochs.insert(query_id, epoch_id); + } Review Comment: This carry-forward keeps the epochs of every other query, but the tests check it only across another query's append (L989-L994). After the Truncate epoch, `streaming_writes_publish_each_epoch_of_a_query_once` checks only `epochs["query"]` (L1008), and no test reads the epochs after a batch write that follows streaming commits. So starting from an empty map on truncate or on a batch write would keep the tests green, while a restarted query `other` would publish its epoch 0 again, although the README says the queries that write to the same destination keep their epochs apart. Could the test assert the whole map after the Truncate epoch, and again after a batch append? ########## sql/native/rust/src/stream.rs: ########## @@ -0,0 +1,987 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::ffi::{c_char, c_int, c_void, CString}; +use std::sync::Arc; + +use arrow_array::ffi::FFI_ArrowArray; +use arrow_array::ffi_stream::FFI_ArrowArrayStream; +use arrow_array::types::{Decimal128Type, DecimalType}; +use arrow_array::{Array, RecordBatch, StructArray}; +use arrow_data::ArrayData; +use arrow_schema::{ffi::FFI_ArrowSchema, DataType, Field, Fields, Schema, SchemaRef, TimeUnit}; + +use super::{c_message, drop_provider, provider_call}; +use crate::{PartitionReader, Result}; + +struct StreamState<'task> { + reader: Option<PartitionReader<'task>>, + // The schema to read, whose columns, Spark types, and nullability each batch must have. + expected: SchemaRef, + // The schema of the stream: that of the first batch, which every batch must have, or + // the schema to read of a reader without batches. Unknown until either is read. + schema: Option<SchemaRef>, + // The schema of the last batch that the reader returned, with the indices of the columns + // to read in it, or None when it has exactly those columns. + projection: Option<(SchemaRef, Option<Vec<usize>>)>, + // The first batch, when get_schema read it to learn the schema. + pending: Option<ArrayData>, + last_error: Option<CString>, + finished: bool, +} + +impl StreamState<'_> { + /// Reads and checks the next batch. The first batch, or the end of the reader, + /// determines the schema of the stream. + fn read_next(&mut self) -> Result<Option<ArrayData>> { + let Some(batch) = self.reader.as_mut().expect("reader is present").next() else { + self.finished = true; + self.schema.get_or_insert_with(|| self.expected.clone()); + return Ok(None); + }; + let batch = self.project(batch?)?; + match &self.schema { + Some(schema) if batch.schema() != *schema => { + return Err(schema_change(schema, &batch.schema()).into()); + } + Some(_) => {} + None => { + if canonical_fields(batch.schema().fields())? + != canonical_fields(self.expected.fields())? + { + return Err("executor reader schema does not match the schema to read".into()); + } + self.schema = Some(batch.schema()); + } + } + let data = StructArray::from(batch).to_data(); + validate_layout(&data)?; + for (column, field) in data.child_data().iter().zip(self.expected.fields()) { + check_values(column, field, field.name(), None)?; + } + Ok(Some(data)) + } + + /// Keeps the columns of the schema to read, in its order, from a batch that may have more, + /// such as all the columns of the source. Resolves the columns once for each schema. + fn project(&mut self, batch: RecordBatch) -> Result<RecordBatch> { + let schema = batch.schema(); + if !matches!(&self.projection, Some((last, _)) if *last == schema) { + self.projection = Some((schema.clone(), projection(&schema, &self.expected)?)); + } Review Comment: No test reaches the re-resolution here. `the_sdk_keeps_the_columns_of_the_schema_to_read_by_name` (L573) exports one batch per stream, and `a_batch_cannot_change_the_schema_of_the_stream` (L970) reads batches with exactly the columns to read, so the projection is `None` both times. If this kept the first batch's indices, a reader returning `[id, flag]` and then `[flag, id]` for the schema to read `[id]` would fail on its second batch with a spurious schema-change error, and every test would still pass. Could a test read two such batches and check that both come back as the schema to read, with their own values? -- 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]
