gengliangwang commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4591134223
########## sql/native/rust/src/bridge.rs: ########## @@ -0,0 +1,1086 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Driver-only handles of sources, scans, streams, and writes, and executor readers restored +//! from serialized values. + +use std::any::Any; +use std::collections::HashMap; +use std::ffi::CString; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use arrow_array::ffi_stream::FFI_ArrowArrayStream; +use arrow_schema::SchemaRef; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; + +use crate::write::{Batch, DriverWrite, DriverWriter}; +use crate::{ + abi, BatchWrite, Capabilities, CommitOffsetInfo, CreateInfo, DataSource, LatestOffsetInfo, + LimitSupport, MicroBatchInfo, MicroBatchStream, MicroBatchStreamInfo, PartitionReaderFactory, + ReadLimit, ReaderContext, Result, ScanBuilder, ScanInfo, ScanPlan, StreamingWrite, + StreamingWriteInfo, TaskContext, WriteInfo, WriteMode, +}; + +#[path = "stream.rs"] +pub(crate) mod stream; + +const STATE_VERSION: u32 = 1; + +type HandleMap<T> = Mutex<HashMap<i64, Arc<Mutex<T>>>>; + +/// One registry per loaded plugin. Provider code runs under a per-handle lock, +/// so independent sources, scans, and streams do not serialize behind a global lock. +pub struct Bridge<S: DataSource> { + next_handle: AtomicI64, + sources: HandleMap<SourceState<S>>, + // The builder of each scan, until Spark plans the scan. + scans: HandleMap<Option<S::ScanBuilder>>, + streams: HandleMap<S::MicroBatchStream>, + writers: HandleMap<Box<dyn DriverWrite>>, +} + +impl<S: DataSource> Default for Bridge<S> { + fn default() -> Self { + Self { + next_handle: AtomicI64::new(1), + sources: Mutex::new(HashMap::new()), + scans: Mutex::new(HashMap::new()), + streams: Mutex::new(HashMap::new()), + writers: Mutex::new(HashMap::new()), + } + } +} + +/// The partitions of a scan or a micro-batch, and the state of its reader: its factory. +pub struct EncodedPlan { + pub state: Vec<u8>, + pub partitions: Vec<Vec<u8>>, +} + +impl<S: DataSource> Bridge<S> { + // Whether the source implements each operation, whose native callbacks the SDK installs. + + pub const READ: bool = <S::ScanBuilder as ScanBuilder>::SUPPORTED; + + pub const MICRO_BATCH_READ: bool = <S::MicroBatchStream as MicroBatchStream>::SUPPORTED; + + pub const WRITE: bool = <S::BatchWrite as BatchWrite>::SUPPORTED; + + pub const STREAMING_WRITE: bool = <S::StreamingWrite as StreamingWrite>::SUPPORTED; + + const CAPABILITIES: Capabilities = Capabilities::implemented(&[ + (Capabilities::BATCH_READ, Self::READ), + (Capabilities::MICRO_BATCH_READ, Self::MICRO_BATCH_READ), + (Capabilities::BATCH_WRITE, Self::WRITE), + (Capabilities::STREAMING_WRITE, Self::STREAMING_WRITE), + ( + Capabilities::BATCH_TRUNCATE, + <S::BatchWrite as BatchWrite>::SUPPORTS_TRUNCATE, + ), + ( + 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), + ( + Capabilities::STREAMING_WRITE, + Capabilities::STREAMING_TRUNCATE, + ), + ] { + if !capabilities.contains(write) { + capabilities = capabilities.without(truncate); + } + } + capabilities + } + + pub fn schema(&self, handle: i64) -> Result<SchemaRef> { + let source = get(&self.sources, handle)?; + let schema = lock(&source).source.infer_schema()?; + stream::validate_schema(&schema)?; + Ok(schema) + } + + pub fn create_reader(&self, handle: i64, schema: SchemaRef) -> Result<i64> { + stream::validate_schema(&schema)?; + let source = get(&self.sources, handle)?; + let builder = { + let source = lock(&source); + require(source.capabilities, Capabilities::BATCH_READ, "batch reads")?; + source.source.new_scan(ScanInfo::new(schema))? + }; + self.insert(&self.scans, Some(builder)) + } + + pub fn push_limit(&self, handle: i64, limit: usize) -> Result<bool> { + let scan = get(&self.scans, handle)?; + let mut scan = lock(&scan); + Ok(builder(&mut scan)?.push_limit(limit)? == LimitSupport::Global) + } + + pub fn prune_columns(&self, handle: i64, columns: &[String]) -> Result<()> { + let scan = get(&self.scans, handle)?; + let mut scan = lock(&scan); + builder(&mut scan)?.prune_columns(columns) + } + + /// Plans a scan, which consumes its builder. + pub fn plan(&self, handle: i64) -> Result<EncodedPlan> { + let scan = get(&self.scans, handle)?; + let builder = lock(&scan) + .take() + .ok_or("the scan has already been planned")?; + encode_plan(builder.plan()?) + } + + pub fn close_reader(&self, handle: i64) -> Result<()> { + remove(&self.scans, handle); + Ok(()) + } + + pub fn create_stream_reader(&self, handle: i64, info: MicroBatchStreamInfo) -> Result<i64> { + stream::validate_schema(&info.schema)?; + let source = get(&self.sources, handle)?; + let stream = { + let source = lock(&source); + require( + source.capabilities, + Capabilities::MICRO_BATCH_READ, + "micro-batch streaming reads", + )?; + source.source.new_micro_batch_stream(info)? + }; + self.insert(&self.streams, stream) + } + + pub fn initial_offset(&self, handle: i64) -> Result<String> { + let stream = get(&self.streams, handle)?; + let offset = lock(&stream).initial_offset()?; + encode_offset(&offset) + } + + pub fn default_read_limit(&self, handle: i64) -> Result<ReadLimit> { + let stream = get(&self.streams, handle)?; + let limit = lock(&stream).default_read_limit(); + limit + } + + /// Decodes the offsets of a request, and encodes the latest offset. + pub fn latest_offset(&self, handle: i64, info: LatestOffsetInfo<String>) -> Result<String> { + let stream = get(&self.streams, handle)?; + let info = LatestOffsetInfo { + start: decode_offset(&info.start)?, + limit: info.limit, + run_end: info.run_end.as_deref().map(decode_offset).transpose()?, + }; + let offset = lock(&stream).latest_offset(info)?; + encode_offset(&offset) + } + + pub fn stream_partitions(&self, handle: i64, start: &str, end: &str) -> Result<EncodedPlan> { + let stream = get(&self.streams, handle)?; + let info = MicroBatchInfo::new(decode_offset(start)?, decode_offset(end)?); + let plan = lock(&stream).plan(info)?; + encode_plan(plan) + } + + pub fn commit_offset(&self, handle: i64, end: &str) -> Result<()> { + let stream = get(&self.streams, handle)?; + let info = CommitOffsetInfo::new(decode_offset(end)?); + let result = lock(&stream).commit(info); + result + } + + pub fn close_stream_reader(&self, handle: i64) -> Result<()> { + remove(&self.streams, handle); + Ok(()) + } + + /// Creates a batch write, or the write of a micro-batch of the streaming query `query_id`, + /// with the state of its task writers. + pub fn create_writer( + &self, + handle: i64, + schema: SchemaRef, + mode: WriteMode, + query_id: Option<String>, + ) -> Result<(i64, Vec<u8>)> { + stream::validate_schema(&schema)?; + let source = get(&self.sources, handle)?; + let (writer, state) = { + let source = lock(&source); + let capabilities = source.capabilities; + let truncate = mode == WriteMode::Truncate; + match query_id { + None => { + require(capabilities, Capabilities::BATCH_WRITE, "batch writes")?; + if truncate { + let overwrite = "the save mode overwrite"; + require(capabilities, Capabilities::BATCH_TRUNCATE, overwrite)?; + } + let write = source.source.new_write(WriteInfo::new(schema, mode))?; + DriverWriter::create(Batch(write))? + } + Some(query_id) => { + require( + capabilities, + Capabilities::STREAMING_WRITE, + "streaming writes", + )?; + if truncate { + let complete = "the output mode complete"; + require(capabilities, Capabilities::STREAMING_TRUNCATE, complete)?; + } + let info = StreamingWriteInfo::new(schema, mode, query_id); + let write = source.source.new_streaming_write(info)?; + DriverWriter::create(write)? + } + } + }; + Ok((self.insert(&self.writers, writer)?, state)) + } + + pub fn commit(&self, handle: i64, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()> { + let writer = get(&self.writers, handle)?; + let result = lock(&writer).commit(epoch_id, messages); + result + } + + pub fn abort(&self, handle: i64, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()> { + let writer = get(&self.writers, handle)?; + let result = lock(&writer).abort(epoch_id, messages); + result + } + + pub fn close_writer(&self, handle: i64) -> Result<()> { + remove(&self.writers, handle); + Ok(()) + } + + pub fn close_source(&self, handle: i64) -> Result<()> { + remove(&self.sources, handle); + Ok(()) + } +} + +/// Opens the executor reader of a partition with factory `F`, using only serialized values. +/// No source, scan, stream, or driver handle registry is created or consulted. +/// +/// # Safety +/// `task` must satisfy TaskContext::from_raw and remain valid until the +/// returned stream is released. The stream's consumer must follow the +/// Arrow C Stream ownership protocol and keep the plugin loaded. +pub unsafe fn open_reader<F: PartitionReaderFactory>( + task: *const abi::SparkDsTaskContext, + schema: SchemaRef, + state: &[u8], + partition: &[u8], +) -> Result<FFI_ArrowArrayStream> { + stream::validate_schema(&schema)?; + let factory: F = decode(state)?; + let (task, partition_index) = unsafe { TaskContext::from_raw(task)? }; + let context = ReaderContext::new(schema.clone(), partition_index, task); + let reader = factory.open(decode(partition)?, context)?; + Ok(unsafe { stream::export(reader, &schema) }) +} + +fn require(capabilities: Capabilities, capability: Capabilities, operation: &str) -> Result<()> { + if capabilities.contains(capability) { + Ok(()) + } else { + Err(format!("source does not support {operation}").into()) + } +} + +/// The builder of a scan that is not planned yet. +fn builder<B>(scan: &mut Option<B>) -> Result<&mut B> { + scan.as_mut() + .ok_or_else(|| "the scan has already been planned".into()) +} + +/// Encodes the factory of a plan, as the state of its reader, and each of its partitions. +fn encode_plan<F: PartitionReaderFactory>(plan: ScanPlan<F>) -> Result<EncodedPlan> { + Ok(EncodedPlan { + state: encode(&plan.factory)?, + partitions: plan.partitions.iter().map(encode).collect::<Result<_>>()?, + }) +} + +fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { + // A provider panic becomes an ABI error. Recover the lock so close can + // still remove and release the handle after that failed call. + mutex.lock().unwrap_or_else(|error| error.into_inner()) +} + +fn get<T>(handles: &HandleMap<T>, handle: i64) -> Result<Arc<Mutex<T>>> { + lock(handles) + .get(&handle) + .cloned() + .ok_or_else(|| format!("unknown or closed native handle: {handle}").into()) +} + +fn remove<T>(handles: &HandleMap<T>, handle: i64) { + let value = lock(handles).remove(&handle); + // Provider destructors run after releasing the registry lock. Repeated + // closes are harmless, and IDs are never reused. + drop_provider(value); +} + +struct SourceState<S> { + source: S, + capabilities: Capabilities, +} + +/// Offsets are compact JSON on a single line, which Spark stores in the checkpoint as they +/// are, so they have no envelope: the library owns their format. +fn encode_offset<T: Serialize>(offset: &T) -> Result<String> { + Ok(serde_json::to_string(offset)?) +} Review Comment: Done in 4ce568b02454: `encode_offset` now needs `DeserializeOwned` and decodes the JSON it wrote, failing the call with that JSON before Spark stores it. The `# Offsets` docs and the README now say NaN and the infinities become `null` and an `Option<f64>` holding one decodes as `None`. Added a unit test for NaN and both infinities. ########## sql/native/rust/src/lib.rs: ########## @@ -0,0 +1,931 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Experimental SDK for native data sources in Rust, over version 1 of the C ABI of Spark, +//! `spark_datasource.h`. +//! +//! Implement [`DataSource`], naming the types of the operations that it implements: a +//! [`ScanBuilder`] for batch reads, a [`MicroBatchStream`] for micro-batch streaming reads, a +//! [`BatchWrite`] for batch writes, and a [`StreamingWrite`] for streaming writes, or +//! [`Unsupported`] for an operation that it does not implement. Then invoke +//! [`export_data_source!`] once in a `cdylib` crate. The SDK +//! owns handles, plan/message serialization, C ABI adaptation, and Arrow import/export. +//! Rust traits stay inside the plugin; they are not an ABI between dynamic libraries. +//! +//! Methods receive their inputs in `#[non_exhaustive]` structs: `*Info` structs on the driver +//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], [`LatestOffsetInfo`], +//! [`MicroBatchInfo`], [`CommitOffsetInfo`], [`WriteInfo`], [`CommitInfo`], [`AbortInfo`], +//! [`StreamingWriteInfo`], [`StreamingCommitInfo`], and [`StreamingAbortInfo`]), `*Context` +//! structs, which carry the live [`TaskContext`], on the executors ([`ReaderContext`] and +//! [`WriterContext`]), and [`HostInfo`], which [`DataSource::init`] receives in every JVM +//! that loads the library, executors included. The methods whose function of the header +//! passes nothing but the size of its info struct yet, [`ScanBuilder::plan`], +//! [`MicroBatchStream::initial_offset`], and the `commit` and `abort` of [`DataWriter`], take +//! no struct: a field added there would be a breaking change of the SDK. + +use std::collections::BTreeMap; + +use arrow_array::RecordBatch; +use arrow_schema::{ArrowError, SchemaRef}; +use serde::de::DeserializeOwned; +use serde::Serialize; + +mod abi; +mod bridge; +mod capabilities; +mod export; +mod host; +mod task; +mod unsupported; +mod write; + +/// Implementation details of [`export_data_source!`] and of the SDK's own tests, not an API. +#[doc(hidden)] +pub mod __private { + pub use crate::bridge::Bridge; + pub use crate::export::{library, Exported}; + + pub mod abi { + pub use crate::abi::*; + } +} + +/// The Arrow crate of [`RecordBatch`], which connectors can use to have the same version of +/// Arrow as the SDK. +pub use arrow_array; +/// The Arrow crate of [`SchemaRef`] and [`ArrowError`], which connectors can use to have the +/// same version of Arrow as the SDK. +pub use arrow_schema; +pub use capabilities::Capabilities; +pub use host::HostInfo; +/// The `log` crate, whose macros write to the log of the Spark driver or executor, with +/// the path of the library, once Spark initializes the library. +/// +/// Any thread can call them, including in the dependencies of the library. Outside +/// Spark, for example in unit tests, their messages are dropped. The SDK sets the level of +/// the `log` crate to that of the log of Spark, such as `Debug` when Spark logs debug +/// messages, so the library does not set it. +pub use log; +pub use task::TaskContext; +pub use unsupported::Unsupported; + +pub type Error = Box<dyn std::error::Error + Send + Sync>; +pub type Result<T> = std::result::Result<T, Error>; +pub type Options = BTreeMap<String, String>; + +// Data sources: Spark creates a DataSource for each operation, and its associated types +// name the operations that the source implements. + +/// What Spark passes to create a data source. +/// +/// Use [`Self::new`] to construct this value outside Spark, and include `..` when +/// destructuring it to allow additional fields. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct CreateInfo { + /// The name of the data source, as listed in the manifest of its package, or in + /// lower case for an installed library. A library that implements several data + /// sources, installed or listed under each of their names, can choose by this name. + pub name: String, + /// The options, with keys in lower case. A capability probe uses the options of the + /// table; an operation may override them with the options of its query. + pub options: Options, +} + +impl CreateInfo { + /// The information of a source created outside Spark, for example in a test. + pub fn new(name: impl Into<String>, options: Options) -> Self { + Self { + name: name.into(), + options, + } + } +} + +/// Driver-side source configuration, schema discovery, and the operations of a source. +/// +/// The associated types name the operations that the source implements, and +/// [`Unsupported`] stands for one that it does not implement: +/// +/// ```rust,ignore +/// impl DataSource for RangeSource { +/// type ScanBuilder = RangeScan; +/// type MicroBatchStream = RangeStream; +/// type BatchWrite = Unsupported; +/// type StreamingWrite = Unsupported; +/// ... +/// } +/// ``` +/// +/// The SDK installs native callbacks and reports capabilities only for the implemented +/// operations, and calls the `new_*` method of an operation only for them. +/// +/// Spark creates a source for each schema inference, scan, stream, and write, including +/// the write of each micro-batch, and may create one only to inspect its capabilities, +/// then drop it. Keep construction lightweight. Scan builders, streams, and writes cannot +/// borrow their source, which Spark drops first. +pub trait DataSource: Send + Sized + 'static { + fn new(info: CreateInfo) -> Result<Self>; + + /// Called once in each JVM when Spark loads the library, before it creates any + /// source. On failure, Spark does not use the library, and the error is logged. + fn init(_host: &HostInfo) -> Result<()> { + Ok(()) + } + + // Schema discovery. + + /// Whether [`infer_schema`](Self::infer_schema) infers the schema of the data. When + /// false, the SDK leaves the native `schema` function unset: Spark then requires a + /// user-specified schema, reports its standard error without one, and never calls + /// `infer_schema`. + const INFERS_SCHEMA: bool = true; + + /// Returns the schema of the data, when the user does not specify one. + fn infer_schema(&self) -> Result<SchemaRef> { + Err( + "DataSource::infer_schema is not implemented: implement it, or set \ + DataSource::INFERS_SCHEMA to false to require a user-specified schema" + .into(), + ) + } + + // Batch reads. + + /// The scan builder of batch reads, which [`new_scan`](Self::new_scan) creates, or + /// [`Unsupported`]. + type ScanBuilder: ScanBuilder; + + /// Creates an independent scan of [`ScanInfo::schema`], which the user may have + /// specified; reject unsupported schemas. + fn new_scan(&self, _info: ScanInfo) -> Result<Self::ScanBuilder> { + Err( + "DataSource::new_scan is not implemented: implement it, or set \ + DataSource::ScanBuilder to Unsupported" + .into(), + ) + } + + // Micro-batch streaming reads. + + /// The stream of micro-batch streaming reads, which + /// [`new_micro_batch_stream`](Self::new_micro_batch_stream) creates, or [`Unsupported`]. + type MicroBatchStream: MicroBatchStream; + + /// Creates the stream of a streaming query that reads the columns of + /// [`MicroBatchStreamInfo::schema`]; reject unsupported schemas. + fn new_micro_batch_stream( + &self, + _info: MicroBatchStreamInfo, + ) -> Result<Self::MicroBatchStream> { + Err( + "DataSource::new_micro_batch_stream is not implemented: implement it, or set \ + DataSource::MicroBatchStream to Unsupported" + .into(), + ) + } + + // Batch writes. + + /// The coordinator of batch writes, which [`new_write`](Self::new_write) creates, or + /// [`Unsupported`]. + type BatchWrite: BatchWrite; + + /// Validate the input schema and create an independent write. Construction may be + /// followed only by Drop, without commit or abort, so it must not make irreversible + /// changes. The SDK calls this only while the instance's capabilities include + /// `BATCH_WRITE`, and passes [`WriteMode::Truncate`] only when they include + /// `BATCH_TRUNCATE`, which the write declares with [`BatchWrite::SUPPORTS_TRUNCATE`]. + fn new_write(&self, _info: WriteInfo) -> Result<Self::BatchWrite> { + Err( + "DataSource::new_write is not implemented: implement it, or set \ + DataSource::BatchWrite to Unsupported" + .into(), + ) + } + + // Streaming writes. + + /// The coordinator of the write of each micro-batch of a streaming query, which + /// [`new_streaming_write`](Self::new_streaming_write) creates, or [`Unsupported`]. + type StreamingWrite: StreamingWrite; + + /// Validate the input schema and create the write of a micro-batch. As with + /// [`new_write`](Self::new_write), construction may be followed only by Drop, so it must + /// not make irreversible changes. The SDK calls this only while the instance's + /// capabilities include `STREAMING_WRITE`, and passes [`WriteMode::Truncate`] only when + /// they include `STREAMING_TRUNCATE`, which the write declares with + /// [`StreamingWrite::SUPPORTS_TRUNCATE`]. + fn new_streaming_write(&self, _info: StreamingWriteInfo) -> Result<Self::StreamingWrite> { + Err( + "DataSource::new_streaming_write is not implemented: implement it, or set \ + DataSource::StreamingWrite to Unsupported" + .into(), + ) + } + + // Instance restrictions. + + /// Returns the operations of this instance. The SDK keeps only those that the source + /// implements, so the default, [`Capabilities::all`], keeps them all. Override this to + /// restrict an instance, for example for a read-only destination. The SDK evaluates + /// it once when Spark creates the source. An instance without operations still + /// supports schema discovery. + fn capabilities(&self) -> Capabilities { + Capabilities::all() + } +} + +// Batch reads: a ScanBuilder negotiates pushdown and plans the scan on the driver, and a +// PartitionReaderFactory opens a reader of each partition on the executors. + +/// What Spark passes to create a scan. +/// +/// Use [`Self::new`] to construct this value outside Spark, and include `..` when +/// destructuring it to allow additional fields. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct ScanInfo { + /// The schema to read: the schema of the source, or one that the user specified. + pub schema: SchemaRef, +} + +impl ScanInfo { + /// The information of a scan created outside Spark, for example in a test. + pub fn new(schema: SchemaRef) -> Self { + Self { schema } + } +} + +/// Negotiates pushdown on the driver, then plans the scan. +/// +/// Spark calls [`push_limit`](Self::push_limit) and [`prune_columns`](Self::prune_columns), +/// each at most once and in this order, then [`plan`](Self::plan), and drops the builder. +/// After a call fails, it makes no other call. It drops a builder without planning it when it +/// does not read the scan, for example to only explain a query, once the scan is no longer +/// referenced, which may be late and on another thread, so a builder must not hold a resource +/// that other operations need exclusively, such as a lock, until Drop. Only the serialized +/// factory and partitions reach the executors. +pub trait ScanBuilder: Send + Sized + 'static { + type Factory: PartitionReaderFactory; + + /// False only for [`Unsupported`], from which the SDK derives the capabilities. + #[doc(hidden)] + const SUPPORTED: bool = true; + + /// Pushes a LIMIT of `limit` rows down to the scan. Return [`LimitSupport::Global`] only + /// if the whole scan then returns at most `limit` rows. Spark pushes a limit only when the + /// query does not filter the rows, since it filters them after reading. + fn push_limit(&mut self, _limit: usize) -> Result<LimitSupport> { + Ok(LimitSupport::Unsupported) + } + + /// Tells the scan the top-level columns that the query needs, in order, so that it can + /// plan to read only them. There may be none, for example for `SELECT count(*)`: the + /// batches then only have a number of rows. Readers get these columns in + /// [`ReaderContext::schema`] whether or not the scan implements this method. + fn prune_columns(&mut self, _columns: &[String]) -> Result<()> { + Ok(()) + } + + fn plan(self) -> Result<ScanPlan<Self::Factory>>; +} + +/// Whether a connector limits the rows produced by the whole scan. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum LimitSupport { + /// The scan may return more rows than the limit. A connector may still cap the + /// rows of each partition on its own: Spark applies its limit after reading. + Unsupported, + /// The whole scan returns at most the limit. Spark still applies its limit. + Global, +} + +/// A driver-created plan containing only serializable values. +/// +/// The SDK serializes the reader factory once and each partition independently. +/// Include snapshot identifiers when needed for repeatable task attempts. Do not +/// put pointers, open files, connections, or process-local resources here. +#[non_exhaustive] +pub struct ScanPlan<F: PartitionReaderFactory> { + pub factory: F, + pub partitions: Vec<F::Partition>, +} + +impl<F: PartitionReaderFactory> ScanPlan<F> { + pub fn new(factory: F, partitions: Vec<F::Partition>) -> Self { + Self { + factory, + partitions, + } + } +} + +/// Serializable configuration from which executors open partition readers. +/// +/// The factory carries configuration or a snapshot descriptor; open connections and +/// other live resources in [`open`](Self::open). Spark passes the schema to read with +/// each partition, so the factory need not carry it. +pub trait PartitionReaderFactory: Serialize + DeserializeOwned + Send + 'static { + type Partition: Serialize + DeserializeOwned + Send + 'static; + + /// Opens a lazy reader of the batches of `partition`, with the columns of + /// [`ReaderContext::schema`]. + /// + /// - Return batches lazily, with bounded memory. + /// - The reader owns its resources and cannot borrow this short-lived factory. It + /// may keep `context` until Spark releases the stream. + /// - Spark may call the reader on different threads, never concurrently, so it must + /// be `Send` but not necessarily `Sync`. + /// - Check [`TaskContext::is_interrupted`] during long operations, and use timeouts + /// for blocking I/O. + /// - Batches must own their buffers, because Spark may release the stream before + /// its batches. Review Comment: Done in 4ce568b02454: The `open` bullet and the README's Arrow contract section now say that releasing a batch runs the Drop of its buffer owners, which may happen after the task ended on another thread (for example a JVM Cleaner thread after a LIMIT), so it should be quick and not block. Both point to the Scope section for panics. ########## sql/native/rust/README.md: ########## @@ -0,0 +1,570 @@ +<!-- +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +--> + +# Rust native data source SDK prototype + +This experimental SDK implements **batch and micro-batch streaming reads, with admission +control, and batch and streaming writes** over version 1 of the C ABI of native data sources, +[`spark_datasource.h`][header], which Spark 4.4.0 introduces. Spark calls the library through +the Java Foreign Function and Memory (FFM) API, so running a library in Spark requires Java 22 +or newer on the driver and executors. The [guide of native data sources][guide] describes the +ABI. + +The Rust and C tests run independently of Spark and Java. The workspace is not +part of Maven/SBT and introduces no Rust requirement for building Spark. This is +an API prototype, not a compatibility commitment. + +The crate, `spark-datasource`, after `spark_datasource.h`, is not published yet: depend on it +with a path dependency on a Spark source tree, as the examples do, until SPARK-61307 publishes +it to crates.io. It is versioned on its own, from 0.x, and may need a breaking release in any +release of Spark: for a new major version of Arrow, whose types it exposes, or for a new kind +of operation, which adds an associated type to `DataSource` that every connector must name. +Growth within an operation can preserve Rust source compatibility, for example by adding +fields to non-exhaustive input structs under the conditions described below. The crate +supports version 1 of the ABI, which Spark supports from 4.4.0 in all the releases of Spark 4. + +The API uses the types of Arrow 58, such as `RecordBatch`, `SchemaRef`, and `ArrowError`, so +a connector must use the same major version of Arrow: the SDK re-exports the crates as +`spark_datasource::arrow_array` and `spark_datasource::arrow_schema`. Upgrading the +major version of Arrow is a breaking change of the SDK. + +The [Range connector][range] is a separate workspace member under +`examples/src/main/rust/native-data-source`, with a C integration test, packaging +helper, and Spark smoke script. The [file sink example][sink] is a separate write-only +connector. All crates share this directory's lockfile and `target` directory. Cargo commands +select the SDK by default; use `--workspace` to include the examples. + +## Connector API and lifecycle + +A connector implements [`DataSource`](src/lib.rs) for construction, schema discovery, +its operations, and optional capability restrictions. `DataSource::new` receives a +`CreateInfo` with the name of the data source and its options. Spark can create and +immediately drop a source just to discover capabilities; schema inference or an +operation need not follow. + +Four associated types name the operations that the source implements, and +`Unsupported` stands for one that it does not implement: + +```rust +impl DataSource for RangeSource { + type ScanBuilder = RangeScan; // batch reads, created by new_scan + type MicroBatchStream = RangeStream; // streaming reads, by new_micro_batch_stream + type BatchWrite = Unsupported; // no batch writes + type StreamingWrite = Unsupported; // no streaming writes + // new, infer_schema, new_scan, and new_micro_batch_stream +} +``` + +Read support uses three pieces: + +* `DataSource::new_scan`: create an independent scan builder from a `ScanInfo`, which + carries the schema to read. +* `ScanBuilder`: negotiate the limit and the columns to read, then consume itself + in `plan()` to return a typed `ScanPlan<Factory>`. +* `PartitionReaderFactory`: serialize executor configuration and open one lazy reader, + an iterator of Arrow batches, from a typed partition and a `ReaderContext`, which + carries the schema to read, the index of the partition in its plan, and a borrowed + `TaskContext`. + +Streaming reads reuse the executor side: `DataSource::new_micro_batch_stream` creates a +`MicroBatchStream` from a `MicroBatchStreamInfo`, which carries the columns to read and the +location of the checkpoint of the source, and the stream plans each micro-batch as a +`ScanPlan` of a `PartitionReaderFactory`; see +[Streaming reads and writes](#streaming-reads-and-writes). + +Write support is independent: a write-only connector sets `ScanBuilder` and +`MicroBatchStream` to `Unsupported` and implements `DataSource::new_write`, `BatchWrite`, +`DataWriterFactory`, and `DataWriter`. Streaming writes add +`DataSource::new_streaming_write` and `StreamingWrite`, with the same task writers. The +write lifecycle is described below. + +The inputs of these methods are `#[non_exhaustive]` structs: `*Info` structs on the driver +(`CreateInfo`, `ScanInfo`, `MicroBatchStreamInfo`, `LatestOffsetInfo`, `MicroBatchInfo`, +`CommitOffsetInfo`, `WriteInfo`, `CommitInfo`, `AbortInfo`, `StreamingWriteInfo`, +`StreamingCommitInfo`, and `StreamingAbortInfo`), `*Context` structs, which carry the live +`TaskContext`, on the executors (`ReaderContext` and `WriterContext`), and `HostInfo`, which +`DataSource::init` receives in every JVM that loads the library, executors included. Fields +may be added to them: construct them with `new`, as in tests, or `HostInfo` with +`HostInfo::default()` and then set its fields, and destructure them with `..`. +`ScanPlan` has a constructor for the same reason. The methods whose function of the header +passes nothing but the size of its info struct yet take no struct: `ScanBuilder::plan`, +`MicroBatchStream::initial_offset`, and the `commit` and `abort` of `DataWriter`. A field +added there would be a breaking change of the SDK, which its 0.x version allows. + +The factory and partition types implement `Serialize` and `Deserialize`, as the commit +messages of writes do. The SDK encodes them with serde in MessagePack, a self-describing binary +format in which structs are maps with the names of their fields, so the serde attributes that +need them, such as `untagged`, `flatten` and `default`, work, including on byte vectors, and +floats, including NaN and the infinities, round-trip as they are. Offsets are JSON instead, +since Spark stores them as text: see [Streaming reads and writes](#streaming-reads-and-writes). +Connections, pointers, and open readers remain in their creating process. +Include a snapshot identifier in the factory or partitions when retrying a task +must read the same snapshot. Several attempts of a task may open readers of the same +partition at the same time, so a reader must not take a resource that another attempt needs +exclusively, and a `ScanBuilder`, which Spark may drop late, must not hold one until Drop. + +```text +Driver: + DataSource::new_scan -> ScanBuilder -> ScanPlan { factory, partitions } + | | + mutable negotiation immutable serialized descriptors + | +Executor, per task: v + restored factory + partition + ReaderContext -> Arrow reader -> Arrow C Stream +``` + +The Rust API maps to the framework's driver-only `ColumnarBatchPlanner` and its +`ColumnarPlannedBatch` containing a serializable `PartitionReaderFactory`. +`ColumnarScanBuilder.build()` builds a single scan and transfers planner +ownership; it does not plan partitions. `ColumnarBatchScan` plans on the first +request for partitions or a reader factory and caches success or failure. + +For a native source, `NativeBatchPlanner` pushes the limit and the columns to read, +each at most once and in this order, then calls `partitions` once, which returns the +partitions and the state of the reader, and closes the native planner handle. The Rust +`ScanBuilder::plan()` consumes its builder in that call, and the SDK encodes the factory +as the state. After a call fails, Spark calls no other function on the handle than its +close function. Batch planner creation remains lazy for scans that do not read in batch. + +The JVM's `NativePartitionReaderFactory` carries only the library location, +source name, read schema, and serialized state. The native executor `read` entry +point gets the kind of the read, batch or micro-batch, and the schema to read with +the state and the partition, so it restores the Rust factory from those bytes without +creating or accessing the driver registry, and passes the schema to the reader in +`ReaderContext`. Closing the driver handles cannot invalidate factory or partition +bytes already copied to Spark, including for retried tasks. + +`ReaderContext::partition_index` is the partition's index in its scan or micro-batch's plan, +not the Spark task's partition ID. One task can read several source partitions, for example +after a coalesce or union, and different scans can reuse the same index. The task's stage +and attempt identifiers are in `ReaderContext::task`; `task_attempt_id()` identifies an +attempt within the Spark application. For writers, `WriterContext::partition_id` is the +Spark task's partition ID and the position of its winning commit message. `TaskContext` +does not expose a partition ID, since the ABI does not supply the task's partition ID for +readers. + +The reader owns its executor resources and cannot borrow its temporary factory. +It may borrow `TaskContext` until the returned Arrow stream is released. Every host +provides the task IDs of version 1 of the ABI, so the SDK rejects a task context shorter +than in Spark 4.4.0, as it rejects the info structures and the read limit that Spark passes to +the calls when they are shorter. It reads a field that a later release appends to one of them Review Comment: Done in 4ce568b02454: Limited the sentence to the read limit and the info structures that have fields besides their size. ########## examples/src/main/rust/native-data-source/src/lib.rs: ########## @@ -0,0 +1,639 @@ +// 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 deterministic range source: `id` in [start, end), and `label = "row-{id}"`. +//! All C ABI and Arrow C Stream plumbing is supplied by the SDK's export macro. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use arrow_array::StringArray; +use arrow_array::{ArrayRef, Int64Array, RecordBatch, RecordBatchOptions}; +use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_datasource::{ + CreateInfo, DataSource, LatestOffsetInfo, LimitSupport, MicroBatchInfo, MicroBatchStream, + MicroBatchStreamInfo, Options, PartitionReader, PartitionReaderFactory, ReadLimit, + ReaderContext, Result, ScanBuilder, ScanInfo, ScanPlan, Unsupported, +}; + +// The largest values of numPartitions and batchSize. +const MAX_PARTITIONS: usize = 100_000; +const MAX_BATCH_SIZE: usize = 1_000_000; + +pub struct RangeSource { + start: i64, + end: i64, + num_partitions: usize, + batch_size: usize, + max_rows_per_trigger: Option<u64>, +} + +pub struct RangeScan { + start: i64, + end: i64, + num_partitions: usize, + limit: Option<usize>, + factory: RangeReaderFactory, +} + +/// Reader configuration travels to each executor; it contains no live objects. +/// Spark passes the columns to read to the reader, so the factory omits them. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RangeReaderFactory { + batch_size: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RangePartition { + start: i64, + end: i64, +} + +/// A streaming read of the range. The range is fixed, so all its rows are available when +/// the query starts: the first micro-batch reads them, unless `maxRowsPerTrigger` limits each +/// micro-batch, and later ones find no new data. +pub struct RangeStream { + start: i64, + end: i64, + num_partitions: usize, + max_rows_per_trigger: Option<u64>, + factory: RangeReaderFactory, +} + +/// The offset of a streaming read: the next row to read. Spark stores it in the checkpoint +/// as `{"next":13}`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct RangeOffset { + next: i64, +} + +impl DataSource for RangeSource { + type ScanBuilder = RangeScan; + type MicroBatchStream = RangeStream; + // A read-only source. + type BatchWrite = Unsupported; + type StreamingWrite = Unsupported; + + fn new(info: CreateInfo) -> Result<Self> { + let options = info.options; + for key in options.keys() { + if !matches!( + key.as_str(), + "start" | "end" | "numpartitions" | "batchsize" | "maxrowspertrigger" + ) { + return Err(format!("Unknown range option: {key}").into()); + } + } + let start = option(&options, "start", 0_i64)?; + let end = option(&options, "end", 100_i64)?; + let num_partitions = option(&options, "numpartitions", 2_usize)?; + let batch_size = option(&options, "batchsize", 1024_usize)?; + let max_rows_per_trigger = options + .get("maxrowspertrigger") + .map(|_| option(&options, "maxrowspertrigger", 0_u64)) + .transpose()?; Review Comment: Done in 4ce568b02454: The Range source now rejects a `maxRowsPerTrigger` above `i64::MAX` when it is created, with "maxRowsPerTrigger must be at most 9223372036854775807". Added the case to the options test and the bound to the README's option table. -- 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]
